C#中委托和事件的简单例子

最近换工作,项目使用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

猜你喜欢

转载自www.cnblogs.com/haley24/p/11829624.html