新聞中心
本文實(shí)例為大家分享了ManualResetEvent的使用方法,供大家參考,具體內(nèi)容如下
創(chuàng)新互聯(lián)于2013年創(chuàng)立,先為克東等服務(wù)建站,克東等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為克東企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
1. 源碼下載:
下載地址:ManualResetEvent
Demo:
2. ManualResetEvent詳解
ManualResetEvent 允許線程通過發(fā)信號(hào)互相通信。通常,此通信涉及一個(gè)線程在其他線程進(jìn)行之前必須完成的任務(wù)。當(dāng)一個(gè)線程開始一個(gè)活動(dòng)(此活動(dòng)必須完成后,其他線程才能開始)時(shí),它調(diào)用 Reset 以將 ManualResetEvent 置于非終止?fàn)顟B(tài),此線程可被視為控制 ManualResetEvent。調(diào)用 ManualResetEvent 上的 WaitOne 的線程將阻止,并等待信號(hào)。當(dāng)控制線程完成活動(dòng)時(shí),它調(diào)用 Set 以發(fā)出等待線程可以繼續(xù)進(jìn)行的信號(hào)。并釋放所有等待線程。一旦它被終止,ManualResetEvent 將保持終止?fàn)顟B(tài)(即對(duì) WaitOne 的調(diào)用的線程將立即返回,并不阻塞),直到它被手動(dòng)重置??梢酝ㄟ^將布爾值傳遞給構(gòu)造函數(shù)來控制 ManualResetEvent 的初始狀態(tài),如果初始狀態(tài)處于終止?fàn)顟B(tài),為 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) { // 阻塞當(dāng)前線程 this._mre.WaitOne(); strThreadID = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("Thread(" + strThreadID + ") is running..."); Thread.Sleep(5000); } } catch(Exception ex) { Console.WriteLine("線程(" + strThreadID + ")發(fā)生異常!錯(cuò)誤描述:" + ex.Message.ToString()); } } } }
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\"停止線程運(yùn)行..."); Console.WriteLine("輸入\"run\"開啟線程運(yùn)行..."); Console.WriteLine("****************************\r\n"); MREDemo objMRE = new MREDemo(); objMRE.CreateThreads(); while (true) { string input = Console.ReadLine(); if (input.Trim().ToLower() == "stop") { Console.WriteLine("線程已停止運(yùn)行..."); objMRE.Reset(); } else if (input.Trim().ToLower() == "run") { Console.WriteLine("線程開啟運(yùn)行..."); objMRE.Set(); } } } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
分享文章:C#ManualResetEvent使用方法詳解
鏈接分享:http://www.dlmjj.cn/article/iigsco.html