最近換工作,項目使用winform進行開發,多線程並行時有時需要使用其他線程創建的控件,或者是需要使用其他窗體中的一些信息(文本框內容,按鈕點擊等),委托和事件使用比較多,因此寫一個簡單的例子記錄一下。
要想使用委托,首先肯定要聲明
//聲明委托 private delegate void TestDelegate(string addText, RichTextBox temp); //委托變量 private TestDelegate test { get; set; }
因為是多線程中使用,所以在聲明委托的線程中寫一個調用委托的方法
//調用委托 private void InvokeDelegate(string addText, RichTextBox temp) { if (temp != null && temp.InvokeRequired) { temp.BeginInvoke(this.test, new object[] { addText, temp }); } }
在另一個線程中進行委托變量實例化以及委托調用
test = new TestDelegate(AddText); InvokeDelegate(_addText, _tempRichTextBox); private void AddText(string addText, RichTextBox temp) { temp.Text += addText + "\r\n"; }
以上就是多線程中使用委托來進行控件使用的簡單例子
再來看一個使用事件進行控件之間消息傳遞
首先聲明委托和事件
//委托 public delegate void DelegateTest(string text); //事件 public event DelegateTest AddTextEvent;
在需要進行消息傳遞的位置進行Invoke(事件的發布)
AddTextEvent?.Invoke(text);
在調用事件的位置(事件的訂閱)
EventTest et = new EventTest(); et.AddTextEvent += new EventTest.DelegateTest(Et_AddTextEvent); private void Et_AddTextEvent(string text) { this.testRichTextBox.Text += text + "\r\n"; }
C#中事件主要是用來在線程之間進行消息傳遞(通信),使用的是發布-訂閱模型。事件Event在類中聲明,包含事件的類就是用來發布事件,稱為publisher,發布器類;其他接收該事件的類就是訂閱事件,稱為subscriber,訂閱器類。
以上就是winform中使用委托和事件來進行線程之間通信的例子。
完整版代碼放在了GitHub:https://github.com/hhhhhaleyLi/DelegateTest