Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Static method in multi-threading

Consider this code:

public class Test
{
        public void Print()
        {
            lock (this)
            {
                System.Threading.Thread.Sleep(10000);
                Console.WriteLine("Print");
            }
        }
        public static void Somthing()
        {
            Console.WriteLine("Somthing");
        }
}

In print method I lock the class and Somthing is a static method. I expect when calling Somthing after ther Print,Somthing run Separately Thread,because I don't have instance of Test for calling Somthing.

private static void Main(string[] args)
{
     var test = new Test();
     test.Print();
     Test.Somthing();
}

But when write above code ,Test locked and then call Somthing.

Why compiler has this behavior?


2 Answers

There is nothing in here that would cause another thread to be used; why would it? your code:

  • creates an instance of Test
  • invokes (callvirt) Print on that instance
    • which takes a Monitor lock around itself (not a good idea, btw)
    • sleeps for 10 seconds
    • writes a line to the console
    • releases the Monitor lock
  • invokes (call) the static Something method
    • which writes a line to the console

No extra threads required. I should emphasize: it would work identically with regards to threads even if you didn't release the Monitor lock (by using Monitor.Enter without a Monitor.Exit); again: lock does not create threads.

A lock simply stops (blocks) other threads from locking the same object for the duration - it creates a mutually exclusive region. It doesn't create threads.

like image 152
Marc Gravell Avatar answered Jul 09 '26 03:07

Marc Gravell


lock just avoids another thread from accessing the code inside the block to access until the handle is returned. In you case, you actually have a single thread (outside lock). The code inside the lock statement doesn't get locked by anything. Code gets executed synchronously meaning - Thread sleeps for the specified time and then calls Something method.

like image 39
Prash Avatar answered Jul 09 '26 05:07

Prash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!