c# - C# 中的多线程 - 更新标签

标签 c# winforms multithreading

所以我有 3 个标签,必须使用随机数同时更新所有三个标签,直到用户单击停止它的按钮。

这是我的开始按钮上的内容

private void start_Click(object sender, EventArgs e)
{
        t1 = new Thread(new ThreadStart(FirstNumber));
        t2 = new Thread(new ThreadStart(SecondNumber));
        t3 = new Thread(new ThreadStart(ThirdNumber));

        t1.Start();
        t2.Start();
        t3.Start();
}

生成随机数的方法是这样的

public void FirstNumber()
{
        int j = r.Next(0, 50);
        int k = r.Next(50, 100);
        for (int i = j; i <= k; i++)
        {
            number1.Text = i.ToString();
            Thread.Sleep(200);
        }
}

调试时出现以下错误:

Cross-thread operation not valid: Control 'number2' accessed from a thread other than the thread it was created on.

我不明白我是如何为每个线程创建控件的,所以非常感谢您的帮助。

还有一件事,用户是否可以在更新标签时单击停止按钮?或者我是否需要添加另一个等待用户输入的线程?

非常感谢!

最佳答案

您只需要在 UI 线程上设置 TextBox 值,而不是其他线程,因此您可以使用 Control.InvokeControl.BeginInvoke在 UI 线程上执行委托(delegate):

 number1.BeginInvoke(new Action(() => { number1.Text = i.ToString(); }));

关于c# - C# 中的多线程 - 更新标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13152075/

相关文章:

c# - Cookie 安全问题

c# - 如何按每个对象的成员对对象列表进行排序?

iphone - (iphone)pushViewController 在后台线程中?

java - 执行器服务关闭

c++ - std::mutex 锁在覆盖新运算符时挂起

c# - Asp.Net中如何实现SQLDependency缓存?

c# - 运行 Scaffold-DbContext 时出现超时错误

c# - Datatable.Dispose() 会让它从内存中删除吗?

c# - MonthCalendar - 禁用日期

c# - 在 C# 中从父级运行子表单进程