我有这个在我的App.xaml:WPF CrossThreadException在App.xaml中与BackgroundWorker的
public App()
{
_backgroundWorker = new BackgroundWorker();
_backgroundWorker.DoWork += new DoWorkEventHandler(DoBackgroundWork);
_backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundCompleted);
_backgroundWorker.RunWorkerAsync();
_splashView = new SplashView();
_splashView.Show();
}
的DoBackgroundWork
方法执行某些数据库设置,然后BackgroundCompleted
事件关闭_splashView
并显示_mainView
。
但是,从BackgroundCompleted
修改_splashView
中的任何内容都会导致出现交叉线程异常,这是我通过后台工作人员设计要解决的问题。我猜这跟App.Xaml
背景工作的方式有关。也许这是一个糟糕的方式来做闪屏?
对,我已经添加了BeginInvoke使它工作。我想知道为什么我在BackgroundCompleted中需要这个。这个事件不应该在UI线程上触发吗?我认为这是BackgroundWorkers的重点。 – ConditionRacer
@ Justin984对不起,我错过了'BackgroundCompleted'抛出异常。它正在抛出,因为不能保证该方法将在哪个线程上执行。逻辑会决定它应该返回到具有事件处理程序的线程,但事实并非如此。 [相似解答](http://stackoverflow.com/questions/818767/backgroundworker-onworkcompleted-throws-cross-thread-exception) –
有趣!我不知道。所以即使在UI线程上创建了backgroundworker,它的完成事件也不能保证在UI线程上触发?我有一些代码来解决! – ConditionRacer