在不同的线程中创建WPF窗口时出现异常

时间:2012-04-10 09:00:47

标签: .net wpf multithreading dispatcher

我有一个WPF应用程序,我在不同的线程中运行一些动画,所以我的主UI线程将响应。我正在使用发布的代码here

Thread thread = new Thread(() =>
{
    Window1 w = new Window1();
    w.Show();

    w.Closed += (sender2, e2) => w.Dispatcher.InvokeShutdown();

    System.Windows.Threading.Dispatcher.Run();
});

thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

它通常可以正常工作,但是在部署系统后,我得到了关于应用程序崩溃的抱怨,其中包含以下堆栈跟踪:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Collections.Generic.List`1.RemoveAt(Int32 index)
   at System.IO.Packaging.PackagePart.CleanUpRequestedStreamsList()
   at System.IO.Packaging.PackagePart.GetStream(FileMode mode, FileAccess access)
   at System.IO.Packaging.PackagePart.GetStream()
   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)   
   at Window1.xaml:line 1   
   at Window1..ctor()

之前有没有人见过这个例外,可以解释那里发生了什么?这个特殊例外的原因是什么?
我正在使用.Net 3.5 SP1

1 个答案:

答案 0 :(得分:1)

看起来System.Windows.Application.LoadComponent不是线程安全的,因此调用Window构造函数会导致错误。

您可以尝试在主线程中创建窗口实例,只在新线程中显示它,但我不确定它是否适合您的应用程序需求。

相关问题