在下面的代码,当BackgroundWorker
推出时,一SynchronizationContext
确实存在,不过,该RunWorkerCompleted处理程序在不同的线程比RunWorkerAsync()
执行,因此抛出异常。为什么?为什么'RunWorkerCompleted'在错误的线程上执行?
而当拨打tempForm
被删除它运行良好。 (以及相同的取代一个Form
一个MessageBox
当存在对。)
(代码显示一个Form
,启动一个BackgroundWorker
引用另一个表格F1后一秒钟,然后示出了该第二表格F1)
public static Form1 f1;
static BackgroundWorker worker = new BackgroundWorker();
[STAThread]
static void Main()
{
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
f1 = new Form1();
using (Form1 tempForm = new Form1()) tempForm.ShowDialog();
//MessageBox.Show("A MessageBox won't cause the exception later. Only the Form does.");
if (SynchronizationContext.Current == null) throw new Exception("This is NOT thrown");
worker.RunWorkerAsync();
Application.Run(f1);
}
static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show(f1, "Inside RunWorkerCompleted");
//Throws: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.
}
static void worker_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(1000);
}
谁能请解释一下是怎么回事?
+1。谢谢。这看起来不错。 – ispiro 2014-09-01 14:38:15