日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

ManualResetEvent用法

發布時間:2023/12/1 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ManualResetEvent用法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

ManualResetEvent 允許線程通過發信號互相通信。通常,此通信涉及一個線程在其他線程進行之前必須完成的任務。

public static ManualResetEvent mre = new ManualResetEvent(false);
ManualResetEvent建立時是把false作為start的初始狀態,這個類用于通知另一個線程,讓它等待一個或多個線程。注意,為了通知或監聽同一個線程,所有的其它線程都能訪問那個類。
等待線程這樣寫:
? mre.WaitOne();
這將引起等待線程無限期的阻塞并等待類來通知。
發信號的線程應該這樣:
? mre.Set();
這樣類就會被通知,值變成true,等待線程就會停止等待。在通知事件發生后,我們就可以使用下面語句把線程置于非終止狀態,導致線程阻止:
? mre.Reset();
一個測試的例子:

using?System;
using?System.Threading;
namespace?ThreadingTester
{
????
class?ThreadClass
????
{
????????
public?static?ManualResetEvent?mre?=?new?ManualResetEvent(false);
????????
public?static?void?trmain()
????????
{
????????????Thread?tr?
=?Thread.CurrentThread;
????????????Console.WriteLine(
"thread:?waiting?for?an?event");
????????????mre.WaitOne();
????????????Console.WriteLine(
"thread:?got?an?event");
????????????
for?(int?x?=?0;?x?<?10;?x++)
????????????
{
????????????????Thread.Sleep(
1000);
????????????????mre.WaitOne();
????????????????Console.WriteLine(tr.Name?
+?":?"?+?x);
????????????}

????????}

????????
static?void?Main(string[]?args)
????????
{
????????????Thread?thrd1?
=?new?Thread(new?ThreadStart(trmain));
????????????thrd1.Name?
=?"thread1";
????????????thrd1.Start();
????????????
for?(int?x?=?0;?x?<?10;?x++)
????????????
{
????????????????Thread.Sleep(
900);
????????????????Console.WriteLine(
"Main:"?+?x);
????????????????
if?(5?==?x)?mre.Set();
????????????????
if?(6?==?x)?mre.Reset();
????????????????
if?(8?==?x)?mre.Set();
????????????}

????????????
while?(thrd1.IsAlive)
????????????
{
????????????????Thread.Sleep(
1000);
????????????????Console.WriteLine(
"Main:?waiting?for?thread?to?stop");
????????????}

????????}

????}

}

運行的結果為:
thread: waiting for an event
Main:0
Main:1
Main:2
Main:3
Main:4
Main:5
thread: got an event
Main:6
Main:7
Main:8
thread1: 0
Main:9
thread1: 1
Main: waiting for thread to stop
thread1: 2
Main: waiting for thread to stop
thread1: 3
Main: waiting for thread to stop
thread1: 4
Main: waiting for thread to stop
thread1: 5
Main: waiting for thread to stop
thread1: 6
Main: waiting for thread to stop
thread1: 7
Main: waiting for thread to stop
thread1: 8
Main: waiting for thread to stop
thread1: 9
Main: waiting for thread to stop

轉載于:https://www.cnblogs.com/fengfeng/archive/2008/06/24/1229037.html

總結

以上是生活随笔為你收集整理的ManualResetEvent用法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。