ManualResetEvent詳解

1. 源碼下載:

    下載地址:http://files.cnblogs.com/tianzhiliang/ManualResetEventDemo.rar

    Demo:

2. ManualResetEvent詳解

    ManualResetEvent 允許線程通過發信號互相通信。通常,此通信涉及一個線程在其他線程進行之前必須完成的任務。當一個線程開始一個活動(此活動必須完成後,其他線程才能開始)時,它調用 Reset 以將 ManualResetEvent 置於非終止狀態,此線程可被視爲控制 ManualResetEvent。調用 ManualResetEvent 上的 WaitOne 的線程將阻止,並等待信號。當控制線程完成活動時,它調用 Set 以發出等待線程可以繼續進行的信號。並釋放所有等待線程。一旦它被終止,ManualResetEvent 將保持終止狀態(即對 WaitOne 的調用的線程將立即返回,並不阻塞),直到它被手動重置。可以通過將布爾值傳遞給構造函數來控制 ManualResetEvent 的初始狀態,如果初始狀態處於終止狀態,爲 true;否則爲 false。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
 
namespace ManualResetEventDemo
{
    class MREDemo
    {
        private ManualResetEvent _mre;
 
        public MREDemo()
        {
            this._mre = new ManualResetEvent(true);
        }
 
        public void CreateThreads()
        {
            Thread t1 = new Thread(new ThreadStart(Run));
            t1.Start();
 
            Thread t2 = new Thread(new ThreadStart(Run));
            t2.Start();
        }
 
        public void Set()
        {
            this._mre.Set();
        }
 
        public void Reset()
        {
            this._mre.Reset();
        }
 
        private void Run()
        {
            string strThreadID = string.Empty;
            try
            {
                while (true)
                {
                    // 阻塞當前線程
                    this._mre.WaitOne();
 
                    strThreadID = Thread.CurrentThread.ManagedThreadId.ToString();
                    Console.WriteLine("Thread(" + strThreadID + ") is running...");
 
                    Thread.Sleep(5000);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("線程(" + strThreadID + ")發生異常!錯誤描述:" + ex.Message.ToString());
            }
        }
 
    }
}
view sourceprint?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ManualResetEventDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("****************************");
            Console.WriteLine("輸入\"stop\"停止線程運行...");
            Console.WriteLine("輸入\"run\"開啓線程運行...");
            Console.WriteLine("****************************\r\n");
 
            MREDemo objMRE = new MREDemo();
            objMRE.CreateThreads();
 
            while (true)
            {
                string input = Console.ReadLine();
                if (input.Trim().ToLower() == "stop")
                {
                    Console.WriteLine("線程已停止運行...");
                    objMRE.Reset();
                }
                else if (input.Trim().ToLower() == "run")
                {
                    Console.WriteLine("線程開啓運行...");
                    objMRE.Set();
                }
            }
             
        }
    }
}


發佈了17 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章