4

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Sounds like a solution :-) Do you have any additional reference to back up this assumption? I have no way to test it, since it only happened once in the field...
No, this is just an idea. You can take a look at code of System.Windows.Application.LoadComponent to find thread-safety issues there. Or you can try to stress test LoadComponent with test that creates many windows simultaneously on different threads to reproduce this bug
Ok, thanks. I'll take a look at it - I've upvoted you, and will accept this answer when I'll be sure it's the real root cause of the exception I've had.
It seems that this was the problem - creating many such user controls in a seperate thread does fail from time to time. I've added lock on the user controls creation - Thanks!
i'm suprised this is an accepted solution: aren't Windows (like all other DependencyObjects) bound to the thread they were created on, i.e. accessing them from another thread causes an AccessViolationException? So creating them on one thread and showing them on another shouldn't be possible...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.