C # multithreading 7-collaboration between threads ManualResetEvent,

Source: Internet
Author: User

C # multithreading 7-collaboration between threads ManualResetEvent,

ManualResetEvent: a manual reset event. It is easy to understand and use for inter-thread synchronization.

private static void MultiThreadSynergicWithManualResetEvent()        {                        ManualResetEvent mre = new ManualResetEvent(false);            Thread thread1 = new Thread(() =>            {                              mre.WaitOne();                mre.Reset();                Console.WriteLine("thread1 work");                mre.Set();                Thread.Sleep(1000);            });            thread1.Start();            Thread thread2 = new Thread(() =>            {                mre.WaitOne();                Console.WriteLine("thread2 work");                Thread.Sleep(1000);            });            thread2.Start();            mre.Set();        }

Note:

1. ManualResetEvent mre = new ManualResetEvent (false) to create a manual reset event. The value of initialState is false, indicating whether to automatically send a reset event notification after creation. false indicates not to automatically send a reset event notification.

2. After the thread starts, run mre. Set () to send a mre notification to the thread that needs to notify the event.

3. The internal mre. WaitOne () indicates that the thread can continue to run only after the arrival of the mre notification. The thread is in the waiting state.

4. mre in the thread. waitOne () followed by mre. reset () indicates the thread that calls the Reset to terminate the notification after receiving the mre notification. Which thread executes the mre first. reset (), which exclusively occupies the notification.

5. The mre. Set () inside the thread. After the thread executes the necessary functions, it starts the notification again and passes it down (downstream transmission is an image metaphor for friends to understand)

Related Article

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.