C# 线程安全操作 WinForm 控件:Invoke 方法详解
在 C# 中,线程操作 WinForm 控件需要使用 Invoke 方法来实现。Invoke 方法允许在 UI 线程上执行委托,从而避免跨线程操作控件时出现的异常。
以下是一个示例代码,展示了如何在线程中更新文本框的内容:
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(() =>
{
// 在线程中更新文本框的内容
UpdateTextBox('Hello from thread!');
}));
thread.Start();
}
private void UpdateTextBox(string text)
{
if (textBox1.InvokeRequired)
{
// 如果当前线程不是 UI 线程,则使用 Invoke 方法在 UI 线程上执行委托
textBox1.Invoke(new Action<string>(UpdateTextBox), text);
}
else
{
// 在 UI 线程上更新文本框的内容
textBox1.Text = text;
}
}
在这个示例中,当用户单击按钮时,会启动一个新的线程,在该线程中调用 UpdateTextBox 方法来更新文本框。在 UpdateTextBox 方法中,首先检查当前线程是否是 UI 线程,如果不是,则使用 Invoke 方法在 UI 线程上执行 UpdateTextBox 方法。如果当前线程是 UI 线程,则直接更新文本框的内容。
原文地址: https://www.cveoy.top/t/topic/nYYC 著作权归作者所有。请勿转载和采集!