C# 中的多线程 - 更新标签 [英] Multithreading in C# - Update Labels

查看:39
本文介绍了C# 中的多线程 - 更新标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have 3 labels and have to update all three of them at the same time using a random number until the user clicks a button that stops it.

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

This is what I have on my start button

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();
}

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

This is what the methods that generate the random numbers look like

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);
        }
}

调试时出现以下错误:

跨线程操作无效:控制number2"从创建它的线程以外的线程访问.

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

我不明白我是如何为每个线程创建控件的,因此感谢您提供任何帮助.

I don't understand how I am meant to create controls for each thread, so any help is appreciated.

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

One more thing, will the user be able to click the stop button while the labels are being updated? Or do I need to add another thread that waits for the user input?

非常感谢!

推荐答案

你只需要在 UI 线程上设置 TextBox 值,其他线程不需要,所以你可以使用 Control.InvokeControl.BeginInvoke 在 UI 线程上执行委托:

You need set TextBox value only on UI Thread, not other threads, so you can use Control.Invoke or Control.BeginInvoke to execute delegate on UI Thread:

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

这篇关于C# 中的多线程 - 更新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆