Reputation:
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
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
Reputation: 1062502
There is nothing in here that would cause another thread to be used; why would it? your code:
Test
callvirt
) Print
on that instance
Monitor
lock around itself (not a good idea, btw)Monitor
lockcall
) the static Something
method
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 lock
ing the same object for the duration - it creates a mutually exclusive region. It doesn't create threads.
Upvotes: 12