C#线程通信与异步委托
生活随笔
收集整理的這篇文章主要介紹了
C#线程通信与异步委托
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
線程的通知機制
AutoResetEvent是線程實現通知操作的重要方法。通常,AutoResetEvent用于通知正在等待線程已發生事件,允許線程通過發信號互相通信。
AutoResetEvent時間對象提供了給我們可以控制線程執行的先后順序,他的常用方法:
Set設置并發送信號
Reset重置信號,也就是使信號無效
WaitOne等待一個信號
WaitAny靜態方法,等待一個信號數組,信號數組里面有任何信號都可以,否則等待
WaitAll靜態方法,等待一個i額信號數組,信號數組里面的信號全部到齊才可以,否則等待
?
創建一個AutoResetEvent對象,構造方法里面需要帶一個bool類型的參數,
AutoResetEvent myResetEvent = new AutoResetEvent(false);
這個參數如果是false表示時間開始是無信號狀態的,當參數為true表示創建的時間開始是有信號的,就相當于使用false參數創建時間后立即設定了Set方法。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading;namespace AutoResetEventTest {class Program{static AutoResetEvent myResetEvent = new AutoResetEvent(false);static int number;static void Main(string[] args){Thread t = Thread.CurrentThread;t.Name = "寫線程";Thread myReaderThread = new Thread(MyReadThreadProc);myReaderThread.Name = "讀線程";myReaderThread.Start();for (int i = 0; i < 10; i++){Console.WriteLine("{0}寫的值是{1}", t.Name, i);number = i;myResetEvent.Set();Thread.Sleep(1);}myReaderThread.Abort();}static void MyReadThreadProc(){while (true){myResetEvent.WaitOne();Console.WriteLine("{0}讀到的值是{1}", Thread.CurrentThread.Name, number);}}} }例程2
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading;namespace AutoResetEventTest {class Program{static void Main(string[] args){Person p = new Person();Thread th1 = new Thread(p.GetCar);th1.Start();Thread th2 = new Thread(p.GetHome);th2.Start();Thread th3 = new Thread(p.GetWife);th3.Start();AutoResetEvent.WaitAll(p.autoEvents);p.ShowHappiness();}}public class Person{public AutoResetEvent[] autoEvents;public Person(){autoEvents = new AutoResetEvent[]{new AutoResetEvent(false),new AutoResetEvent(false),new AutoResetEvent(false)};}public void GetCar(){Console.WriteLine("撿到寶馬");autoEvents[0].Set();}public void GetHome(){Console.WriteLine("賺到房子");autoEvents[1].Set();}public void GetWife(){Console.WriteLine("騙到老婆");autoEvents[2].Set();}public void ShowHappiness(){Console.WriteLine("好成功哦,好幸福!!!~~~");}} }?
例程3 異步回調
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading;namespace AutoResetEventTest {class Program{public delegate int TaskDelegate(object obj, int ms);public static int GouDui(object obj, int ms){Thread t = Thread.CurrentThread;t.Name = "灰太狼";Console.WriteLine("老板給了{0}元,讓偉大的{1}來勾引你,識相的話趕緊上鉤", obj.ToString(), t.Name);Thread.Sleep(ms);return 3000;}static void TakesAWhileCompleted(IAsyncResult ar){//判斷IAsyncResult對象是否有效,為空則拋出異常if(ar == null){throw new ArgumentNullException("ar");}//將ar對象中AsyncState屬性強類型轉換為TaskDelegate委托類型TaskDelegate d1 = ar.AsyncState as TaskDelegate;//跟蹤檢查d1是否有效,如果無效則顯示提示消息System.Diagnostics.Trace.Assert(d1 != null,"無效的對象類型");//執行委托方法,并將結果交給變量resultint result = d1.EndInvoke(ar);Console.WriteLine("結果泡了{0}個漂漂的mm",result);}static void Main(string[] args){Thread t1 = Thread.CurrentThread;t1.Name = "單行道酒吧";Console.WriteLine("去{0}給我勾搭幾個mm回來!超時每秒摳你100塊工資", t1.Name);//為委托指定執行方法TaskDelegate t = GouDui;//使用魏國的BeginInvoke方法為所委托的方法賦值,并將執行結果交給IasyncResult接口IAsyncResult ir = t.BeginInvoke(600000, 1000 * new Random().Next(5), TakesAWhileCompleted, t);//Thread.Sleep(2000);//int i = 0;//while (!ir.IsCompleted)//{// i++;// Console.WriteLine(i.ToString());// //方法1 // //Thread.Sleep(100);// //方法2// if (ir.AsyncWaitHandle.WaitOne(100, false))// {// Console.WriteLine("怎么還不回來,再扣就把錢扣完了!");// break;// }//}////獲取委托方法執行后返回的值//int result = t.EndInvoke(ir);//Console.WriteLine("報告老板,我一共給你勾兌了{0}個超級mm", result.ToString());//if (i >= 1)//{// Console.WriteLine("非常好,課時你耽誤了{0}個小時,所以扣除你{1}塊的報酬", i.ToString(), (100 * i).ToString());//}//else//{// Console.WriteLine("小伙子不錯哦。哥很欣賞你!");//} Console.ReadKey();}} }轉載于:https://www.cnblogs.com/Mysterious/p/3429492.html
總結
以上是生活随笔為你收集整理的C#线程通信与异步委托的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一步一步学Silverlight 2系列
- 下一篇: 开博啦!!!