如何从另一个线程将文本设置为标签?

时间:2019-09-01 11:53:24

标签: c# multithreading winforms

我不熟悉多线程编程,我只了解一些基础知识。 我想设置一个值,例如从另一个线程到主线程的标签文本(我什至不知道我对主线程的理解是正确的,但是当您看到代码时,您会做我想做的事情) 我还需要一种解决方案来为其他控件和控件的值工作(例如按钮的位置)

static int s = 0;
        void v()
        {
            for (int i = 0; i > -1; i++)
              { 
                s++;
                label1.Text = s.ToString();
              }

        }   
private void buttonX1_Click(object sender, EventArgs e){

            ThreadStart ts = new ThreadStart(v);
            Thread trd = new Thread(ts);
            trd.Start();
}

那是我的整个代码,我只有一个label和一个button 当我点击button时出现此错误:

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

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

如果您的V方法返回字符串,则可以尝试以下操作:

private async void buttonX1_Click (object sender, EventArgs e) {

    string str = await Task.Factory.StartNew(()=> v());

    label1.Text = str;
}

答案 1 :(得分:0)

使用Invoke进行跨线程

this.Invoke((MethodInvoker)delegate { label1.Text = s.ToString(); });

简而言之,C#中的

委托类似于C / C ++中的函数指针。有关更多信息,请查看此link