C # Thread lecture series (5): Synchronous technology Monitor

Source: Internet
Author: User
Tags exit exception handling thread

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
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.