Posted by: MarkWPF
Have you ever been in the situation where you’d thought you were in the UI thread nice and safely, but got the exception message:
The calling thread cannot access this object because a different thread owns it”
What this means is that you have created an object on a thread (usually UI thread), and are then trying to access it from another thread at runtime.
Maybe from a worker thread running an event handler.
To fix it, you need to use the very handy Dispatcher class, which will marshall your call to the correct thread.
You need to use the BeginInvoke (asynchronous) or the Invoke method.
However, you don’t want to have huge numbers of delegate definitions all over your code, so use an anonymous method instead.
The trick is to make sure the returned type from the anonymous delegate is one that matches what the Invoke method expects
If the correct thread happens to be the UI thread you can do the following:
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal, (DispatcherOperationCallback)delegate(object arg)
// do sommat