【发布时间】:2015-04-28 09:28:00
【问题描述】:
c# 线程中的 BackgroundWorker 是否安全?
我问这个的原因是因为我得到了一个
在一个线程上创建的控件不能 成为一个控件的父级 不同的线程
例外。这是我的DoWork 事件代码:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var openFile = document.Open(MyFileName);
e.Result = openFile;
}
其中document 是在创建父窗体时初始化的UI 控件。在Open 方法期间,document 中的各种属性将被填充。
我尝试更改要调用的代码,但同样的问题仍然存在。即,
document.GetType().GetMethod("Open)".Invoke(document, new object[]{MyFileName})
将产生与上述相同的错误。
知道如何操作document 控件吗?也就是说,如何让上面的代码工作?
编辑:有人建议我使用Control.Invoke,但它仍然不起作用(两个线程都挂了)。这是我试过的代码:
private delegate bool OpenFile(string filePath);
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
OpenFile oF = new OpenFile(document.Open);
var openFile = Invoke(oF, MyFileName); // it doesn't really matter whether I use BeginInvoke or Invoke, or other Control.Invoke, the end result is the same. Both the main thread hosting the document and the thread that launches the UI hanged.
e.Result = openFile;
}
【问题讨论】:
标签: c# winforms backgroundworker