跨线程操作无效 [英] Cross-thread operation not valid

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

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the">Cross-thread操作无效:控制从它在创建一个线程比其他线程访问

Possible Duplicate:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

好吧,我知道这是为什么给我这个错误:

Okay, I know why this is giving me this error:

跨线程操作无效:   控制Form1的从一个线程访问   比它创建线程等   上。

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

但是......我怎样才能让这是否可行?

But... How can I make this workable?

System.Threading.Thread t = new System.Threading.Thread(()=>
{
   // do really hard work and then...
   listView1.Items.Add(lots of items);
   lots more UI work
});
t.Start();

我不何时或如何线程完成在意,所以我真的不关心任何幻想或以上复杂的ATM,除非与UI在一个新的线程时,这会让事情变得更加简单。

I don't care when, or how the Thread finishes, so I don't really care about anything fancy or over complicated atm, unless it'll make things much easier when working with the UI in a new Thread.

推荐答案

您不能。 UI操作必须拥有线程上执行。期。

You can't. UI operations must be performed on the owning thread. Period.

您的什么能的做,对孩子线程创建所有这些项目,然后调用 Control.Invoke ,做你的数据绑定存在。

What you could do, is create all those items on a child thread, then call Control.Invoke and do your databinding there.

或者使用的BackgroundWorker

    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += (s, e) => { /* create items */ };
    bw.RunWorkerCompleted += (s, e) => { /* databind UI element*/ };

    bw.RunWorkerAsync();

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

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