標籤:style blog http color io os ar 使用 sp
1.事件模型建立在委託的基礎上。
2,定義事件編譯器會做三個動作,第一個構造具有委託類型的欄位,事件發生時會通知這個列表中的委託。
第二個構造的是一個添加關注的方法+=。
第三個構造是一個登出事件關注的方法-=。
3,一個對象不再希望接收事件通知時應該登出對事件的關注,只要一個對象仍向事件登記了一個方法,這個對象不能記憶體回收,所以你的對象若實現了IDisposable的Dispose方法,應該登出對所有事件的關注。
4,-=,remove一個不存在的委託時,不會報錯。
下面是一個定義事件的標準寫法:引用http://blog.csdn.net/sun_dragon/article/details/8726681
1,定義一個類型來容納所有應該發送給事件通知接收者的附加資訊
2,定義事件成員
3,定義負責引發事件的方法來通知事件的登錄物件
class PriceChangedEventArgs : EventArgs { public readonly decimal LastPrice; public readonly decimal NewPrice; public PriceChangedEventArgs(decimal lp, decimal np) { LastPrice = lp; NewPrice = np; } }
/// <summary> /// 擴充方法,用來封裝這個線程的邏輯安全 /// </summary> public static class EventArgExtensions { public static void Raise<TEventArgs>(this TEventArgs e,object sender,ref EventHandler<TEventArgs> eventDelegate)where TEventArgs:EventArgs { //Interlocked需要4.5環境 //處於安全執行緒考慮,現在將委託欄位的引用複製到一個臨時欄位中 EventHandler<TEventArgs> temp = Interlocked.CompareExchange(ref eventDelegate, null, null); if (temp != null) temp(sender, e); } }
class Stock//即是廣播又是接收 { decimal price; //string symbol = "stock"; public event EventHandler<PriceChangedEventArgs> PriceChanged; public decimal Price { get { return price; } set { if (price != value) { OnPriceChanged(new PriceChangedEventArgs(price, value));//事件觸發 } price = value; } } //簡單寫法,通常這個就夠了 //protected virtual void OnPriceChanged(PriceChangedEventArgs e) //{ // if (PriceChanged != null) // PriceChanged(this, e); //} /// <summary> /// 安全執行緒寫法,事件主要在單線程中使用,安全執行緒並不是一個問題,先記下有這個東西 /// 考慮這個線程競態條件應該意識到一個方法可能在從事件的委託鏈中移除後得到調用 /// </summary> /// <param name="e"></param> protected virtual void OnPriceChanged(PriceChangedEventArgs e) { e.Raise(this,ref PriceChanged); } }
最後是調用
class EvenManage { static void priceChangeInMain(Object sender, PriceChangedEventArgs e) { System.Console.WriteLine(sender.ToString()); System.Console.WriteLine("last price" + e.LastPrice + "\nnew price" + e.NewPrice); } public static void text() { Stock s = new Stock(); s.Price = 100M;//這時沒有調用priceChangeInMain,因為沒有添加事件 s.PriceChanged += priceChangeInMain; s.Price = 200M;//添加完事件之後的觸發調用了priceChangeInMain } }
【CLR in c#】事件