C#線程同步手動重設事件——ManualResetEvent

來源:互聯網
上載者:User

標籤:

和AutoResetEvent類的區別是,Manual一旦set後不會自動reset,會允許存取所有waitone的線程,而autoresetevent每一次set之後只會允許存取一個waitone的線程,然後立即自動reset。這就是自動和手動的區別,實際上說的是自動reset和手動reset。

這裡就貼一段翻譯註釋的msdn官方代碼吧。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace myTest{    class Program    {        private static ManualResetEvent mre = new ManualResetEvent(false);        static void Main(string[] args)        {            Console.WriteLine("\n開啟3個被ManualResetEvent阻塞的線程,並分別命名:\n");            for (int i = 0; i <= 2; i++)            {                Thread t = new Thread(ThreadProc);                t.Name = "Thread_" + i;                t.Start();            }            Thread.Sleep(500);            Console.WriteLine("\n當所有的線程都start後,按下斷行符號鍵以運行ManualResetEvent的set方法" +                              "\n來釋放所有線程的阻塞狀態.\n");            Console.ReadLine();            mre.Set();            Thread.Sleep(500);            Console.WriteLine("\n一旦ManualResetEvent對象收到了set的訊號,後面再調用WaitOne()方法的線程" +                              "\n就不會被阻塞了.按下斷行符號鍵查看結果.\n");            Console.ReadLine();            for (int i = 3; i <= 4; i++)            {                Thread t = new Thread(ThreadProc);                t.Name = "Thread_" + i;                t.Start();            }            Thread.Sleep(500);            Console.WriteLine("\n按下斷行符號鍵調用 Reset(), 這樣後邊再啟動的線程調用waitone()時又會被阻塞了" );            Console.ReadLine();            mre.Reset();            // 啟動一個被ManualResetEvent阻塞的線程            Thread t5 = new Thread(ThreadProc);            t5.Name = "Thread_5";            t5.Start();            Thread.Sleep(500);            Console.WriteLine("\n按下Enter鍵調用 Set() 並結束此次示範.");            Console.ReadLine();            mre.Set();Console.ReadLine();                   }        private static void ThreadProc()        {            string name = Thread.CurrentThread.Name;            Console.WriteLine(name + " 啟動並調用 mre.WaitOne()");            mre.WaitOne();            Console.WriteLine(name + " 退出.");        }    }}

 

C#線程同步手動重設事件——ManualResetEvent

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.