在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/eOug 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录