1

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.

Otiel
  • 18,404
  • 16
  • 78
  • 126
unos baghaii
  • 77
  • 1
  • 9

1 Answers1

2

Is there any way to lock method1() for any instances ?

Yes. If you make the object which the lock is using a static one, it will look it across any instance of the type, and not the instance:

private static object globalLock = new object();

public bool Method1()
{
    lock (globalLock)
    {
        Thread.Sleep(15000);
        return true;
    }
}

Note that in general, locking on the this instance is considered bad practice, for the reason that you cannot know which other objects are using your object as a locking mechanism. That's why it is usually preferred to have a local, self contained object which is used as a lock.

More on that per the MSDN documentation or in Why is lock(this) {...} bad?.

Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321