需要C#线程中的跨线程操作帮助 [英] Need a help for cross thread operation in C# Threads

查看:104
本文介绍了需要C#线程中的跨线程操作帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好!

我在ma测试程序中收到一个称为跨线程操作无效"的异常.我知道该错误.但是我不知道如何解决它.请对此事发表评论.谢谢大家.

这是我的简单代码:

Hello!

I got an exception called cross thread operation invalid in ma test programme.I knw the error.But I dnt knw how to fix it.Please comment on this matter.Thank you all.

Here is my simple code:

private void button1_Click(object sender, EventArgs e)
       {
           Thread thr1 = new Thread(adddata);
           thr1.Start();
           //if (thr1.IsAlive)
             //  addvalue();
       }
       private void adddata() {
           for (int i = 0; i < 20;i++) {
               listBox1.Items.Add(i);
           }
       }
       private void addvalue() {
           int a = 0;
           for (int j = 0; j < 20;j++ ) {
              listBox2.Items.Add(listBox1.Items[0].ToString());
           }
       }



[edit]已添加代码块-OriginalGriff [/edit]



[edit]Code block added - OriginalGriff[/edit]

推荐答案

大多数控件不允许从UI线程以外的线程访问.因此,这些控件具有可以从其他线程调用的invoke方法.

您的AddData可以这样写,以便它也可以从其他线程运行.

Most controls dont allow to be accessed from a thread other than the UI thread. Therefore, these controls have an invoke method which can be called from a different thread.

Your AddData could be written like this so that it will also function from a different thread.

public void AddData()
{
  if (this.InvokeRequired)
  {
    // call method on the ui thread...
    this.Invoke(new MethodInvoker(AddData));
  }
  else
  {
    // In the ui thread
    for (int i = 0; i < 20; i++)
    {
      listBox1.Items.Add(i);
    }
  }
}



希望这会有所帮助.



Hope this helps.


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

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