In the previous lecture, we introduced the use of lock to achieve synchronization between threads. In fact, this lock is a decoy for C #, which compiles the lock statement into a call to the Monitor class when the C # compiler compiles it. Let's look at the following C # source code:
public static void MyLock ()
{
Lock (typeof (program))
{
}
}
The code above synchronizes the mylock with the lock statement, which is compiled into IL, as shown in Figure 1.
Figure 1
As you can see from the area marked above, a lock statement is compiled into the Enter and exit methods that call monitor. Monitor is in the System.Threading namespace. Lock function is equivalent to directly call the entry method of monitor, the difference is that the lock method at the end, will automatically unlock, of course, in the IL is called the Monitor exit method, but in the C # program, it appears to be automatically unlocked, which is similar to C # can automatically release resources, such as databases, by using statements in the However, if you use the monitor class directly in the C # source program, you must call the Exit method to explicitly unlock it. As shown in the following code:
Monitor.entry (Lockobj);
Try
{
Lockobj area of the same cloth
}
catch (Exception e)
{
Exception handling code
}
Finally
{
Monitor.Exit (lockobj); Unlock
}