samedi 18 avril 2015

Lock a part of code for any instances

Can I lock a part of code for any instances ?


consider this



public bool method1()
{
lock (this)
{
Thread.Sleep(15000);
return true;
}
}


and then in First project I call it as :



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();


and then in Second project I call it as above .


Is there any way to lock method1() for any instances ? I mean First project calls the method1 and then Second Project calls it too.Second Project has to wait till the first one passes the lock .






Aucun commentaire:

Enregistrer un commentaire