user1968030
user1968030

Reputation:

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?

Upvotes: 1

Views: 1127

Answers (2)

Prash
Prash

Reputation: 1122

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.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062502

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.

Upvotes: 12

Related Questions