学堂 学堂 学堂公众号手机端

在C#中使用Invoke方法可以在不同线程之间进行通信,通常用于在UI线程中更新UI控件

lewis 1年前 (2024-03-20) 阅读数 4 #技术

在C#中使用Invoke方法可以在不同线程之间进行通信,通常用于在UI线程中更新UI控件。下面是一个简单的示例:

publicpartialclassForm1:Form { publicForm1() { InitializeComponent(); } privatevoidUpdateTextBox(stringtext) { if(textBox1.InvokeRequired) { textBox1.Invoke(newMethodInvoker(delegate{textBox1.Text=text;})); } else { textBox1.Text=text; } } privatevoidbutton1_Click(objectsender,EventArgse) { Threadt=newThread(()=> { UpdateTextBox("Hellofromanotherthread!"); }); t.Start(); } }

在上面的示例中,我们定义了一个UpdateTextBox方法,该方法用于更新textBox1控件的文本。在button1_Click事件中,我们创建了一个新线程,并在其中调用UpdateTextBox方法。由于更新UI控件必须在UI线程中进行,因此我们在UpdateTextBox方法中使用Invoke方法来确保在UI线程中更新textBox1的文本。


版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门