學習|C#的EventHandler的委託使用


學更好的別人,swift

作更好的本身。微信

——《微卡智享》app




本文長度爲3661,預計閱讀10分鐘



前言dom


上一篇發了一個視頻,關於車輛經過系統的場景模擬,在這個項目中,主要想介紹一下使用中距離的讀卡器對車輛上的RFID卡進行身份識別,其中讀卡這塊的核心就是用到了EventHandler的委託和線程的處理,看了一下原來的C#文章中,之前沒有介紹過EventHandler的委託,因此這篇簡單先介紹一下這個,後面的文章會結合EventHandler的委託和線程作一個模擬當時環境小Demo。




EventHandler簡介ide

微卡智享工具

EventHandler就是一個事件處理器,將一個事件與處理事件的方法聯繫起來的一種機制。 說人話就是:我是小明,如今想邀請小紅出去玩,小紅說要吃完飯後才能出來。那原來設計這樣的話,我須要定時去小紅那看看她吃沒吃完飯,這樣一直等到她吃完後咱們再一塊兒出去,而採用EventHandler委託的話,就是吃飯的事小紅本身處理,等吃完後他發送一個消息通知我吃完了,而後咱們一塊兒出去就好了。測試



EventHandler使用

# 說明
1 聲明一個EventArgs的子類,傳遞參數
2 聲明委託對象,執行方法,將方法綁定委託對象
3 開啓EventHandler的委託


EventHandler實現flex

微卡智享ui

打開VS後新建了一個threaddemo的項目,這個項目Demo當線程一塊兒講了後我會發上來。


01this

建立EventArgs子類


建立一個testEvent的子類,繼承自EventArgs,而後定義了一個字符串和一個整數類型,用於記錄返回一內容和當前的ID。

namespace threaddemo{ public class testEvent :EventArgs { public string datastr;
public int id;
public testEvent(string str,int id) { datastr = str; this.id = id; } }}


02

定義接口,寫接口實現方法


新建一個inftest的接口,上面是用interface而不是class,定義了三個方法。
namespace threaddemo{ interface Inftest { event EventHandler<testEvent> DataReceived; void Stop(); void Start(); }}

新建一個CTest的類,繼承自Inftest

這個類主要是寫了一個實現的方式,其中重寫了start和stop的方法,及咱們定義的DataReceived的的處理方式



CTest的代碼
using System;using System.Collections.Generic;using System.Drawing.Text;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;
namespace threaddemo{ public class CTest : Inftest,IDisposable { public int id;
private AutoResetEvent exitEvent;
private Thread thread;
private int waitTime = 100;
private bool disposed = false;
private bool IsRunning;
public int cs = 0; public CTest(int _id) { id = _id; exitEvent = new AutoResetEvent(false); thread = new Thread(ReadThreadRun); thread.IsBackground = true; }

public event EventHandler<testEvent> DataReceived;
public void Dispose() { // Dispose(true); GC.SuppressFinalize(this); }
protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { try { Stop();
} catch (Exception) {
} } disposed = true; } }
public void Start() { IsRunning = true; thread.Start(); }
public void Stop() { IsRunning = false; exitEvent.Reset(); exitEvent.Set(); RaiseDataReceived("手動中止"); }

public void Reset() { exitEvent.Reset(); exitEvent.Set(); }
public void setcs(int _cs) { cs = _cs;
}

private void RaiseDataReceived(string msg) { DataReceived?.Invoke(this, new testEvent(msg, id)); }
/// <summary> /// 接收線程 /// </summary> private void ReadThreadRun() { while (IsRunning) { try { if (exitEvent.WaitOne(waitTime)) { if (IsRunning) { Thread.Sleep(1000); id++; if (id % 5 == 0) { throw new Exception("餘數:0"); }else if (id % 5 == 1) { try { throw new Exception("故意出錯"); } catch(Exception ex) { RaiseDataReceived(ex.Message); Reset(); } } RaiseDataReceived("狀態:重啓"); } else { Thread.Sleep(1000); RaiseDataReceived("中止"); } }
Random rd = new Random(); int count = rd.Next(0, 13); if (count < 10) { RaiseDataReceived(count.ToString()); } else if (count == 10) { throw new Exception("throw 數字:" + count); } else { RaiseDataReceived("數字:" + count + " Reset"); Reset(); } } catch (Exception ex) { RaiseDataReceived("error " + ex.Message); Reset(); }
//Thread.Sleep(100); } } }}


03

開啓委託


在Form的主窗體代碼中,定義好了CTest的類。

寫一個DataReceived的觸發事件。
 private void _test_DataReceived(object sender, testEvent e) {
try { TextShowNew(richTextBox1, e.datastr); int count = -1; try { count = Convert.ToInt32(e.datastr); } catch(Exception ex) { count = -1; }

if (count >= 0) { CItem item = new CItem(0, count, "測試" + count, DateTime.Now); ht.checkHashTest(item, 5000); }
if (!ht.checkDatetime(dtclear, 5000)) { ht.RemoveHashTableFromTime(5000); dtclear = DateTime.Now; } } catch (Exception ex) { TextShowNew(richTextBox1, ex.Message); } }

點擊按鈕初始化時,使用+=剛纔定義的方法進行委託。
 private void Openinf() { try { if (_test != null) { _test.Stop(); _test.Dispose(); } _test = null; _test = new CTest(idx); _test.DataReceived += _test_DataReceived; _test.Start();  TextShowNew(richTextBox1, idx + "開啓"); idx++; } catch (Exception ex) { TextShowNew(richTextBox1, "Error:" + ex.Message, 1); } }
完成上面這三步,咱們的基本委託就能夠實現了。



Demo運行效果


上面的Demo是整個運行的效果,下一篇咱們講線程的時候會整個講一下這個Demo怎麼用於模擬讀卡器的運行狀況。




掃描二維碼

獲取更多精彩

微卡智享




「 往期文章 」


unity3D練習

筆記|C#騰訊雲支付SDK遇到的問題及解決

分享|本身平時經常使用的幾款效率工具




本文分享自微信公衆號 - 微卡智享(VaccaeShare)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索