C# 为任何实例锁定代码的一部分
我可以为任何实例锁定部分代码吗 想想这个C# 为任何实例锁定代码的一部分,c#,reflection,locking,C#,Reflection,Locking,我可以为任何实例锁定部分代码吗 想想这个 public bool method1() { lock (this) { Thread.Sleep(15000); return true; } } 在第一个项目中,我称之为: Assembly testAssembly = Assembly.LoadFile(@"C:\UsersLockTest\ClassLibrary1\bin\Debug\ClassLibrary1.dll"); Type
public bool method1()
{
lock (this)
{
Thread.Sleep(15000);
return true;
}
}
在第一个项目中,我称之为:
Assembly testAssembly = Assembly.LoadFile(@"C:\UsersLockTest\ClassLibrary1\bin\Debug\ClassLibrary1.dll");
Type calcType = testAssembly.GetType("ClassLibrary1.Class1");
object calcInstance = Activator.CreateInstance(calcType);
var x = (bool)calcType.InvokeMember("method1",BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,null, calcInstance, null);
Console.WriteLine("First project " + x);
Console.ReadLine();
然后在第二个项目中,我将其称为如上所述
是否有任何方法可以锁定任何实例的method1()
?我的意思是第一个项目调用method1,然后第二个项目也调用method1。第二个项目必须等到第一个项目通过锁
是否有任何方法可以锁定任何实例的method1()
对。如果将锁所使用的对象设为静态对象,则该对象将在该类型的任何实例中查看,而不是在该实例中:
private static object globalLock = new object();
public bool Method1()
{
lock (globalLock)
{
Thread.Sleep(15000);
return true;
}
}
请注意,通常情况下,锁定此
实例被认为是不好的做法,因为您无法知道哪些其他对象正在使用您的对象作为锁定机制。这就是为什么人们通常倾向于使用一个本地的、自包含的对象作为锁
更多关于这一点,请参阅或