Amittai Shapira
Amittai Shapira

Reputation: 3827

Exception when creating WPF window in a different thread

I have a WPF application, and I'm running some animation in a different thread, so my main UI thread will be responsive. I'm using the code posted 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();

It usually works fine, but after the system was deployed I got complaint about application crash with the following stack trace:

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()

Have anyone seen this exception before and can explain what is going on there? What could be the reason for this specific exception?
I'm using .Net 3.5 SP1

Upvotes: 4

Views: 797

Answers (1)

Nikolay
Nikolay

Reputation: 3828

It looks like System.Windows.Application.LoadComponent is not thread-safe so your call to Window constructor can cause error.

You can try to create window instances in the main thread and just show it in the new thread, but I am not sure if that fits to your application needs.

Upvotes: 2

Related Questions