The calling thread cannot access this object because a different thread owns it [duplicate]
Following code might help you solve the issue of updating a gui element from another thread :
Module level
delegate void updateCallback(string tekst);
This is the method to update your element :
private void UpdateElement(string tekst)
{
if (element.Dispatcher.CheckAccess() == false)
{
updateCallback uCallBack = new updateCallback(UpdateElement);
this.Dispatcher.Invoke(uCallBack, tekst);
}
else
{
//update your element here
}
}
When working with WPF be aware that if you create a UI object in one thread you can't access it from another thread. Your UI objects should (typically) be created the UI thread, and then you need the UI thread to access them later. No other thread will be able to access objects created on the UI thread.
If you need to access a UI object from another thread you need the UI thread Dispatcher, and then you can use this to invoke calls on the UI thread.
I've spent many hours in frustration of similar problems to this - believe me.. Check out this question - it gave me a lot of useful information on the subject.
You can look through this classes in reflector. Exception will rise in cb.Freeze(). In
CroppedBitmap cb = new CroppedBitmap(bf, new Int32Rect(1,1,5,5));
case constructor did something like this:
this.this.Source = source;
So source wasn't created in current thread, and so exception will rise. In
new WriteableBitmap(bf)
case, constructor synchronize with bf object and new source is created in current thread, so, no exceptions will rise. If you are interested in In Depth details, you can always reflect base libraries with Reflector :)
I had the same issue and fixed the problem by creating my UIElement
in the UI thread by using its dispatcher (that can be accessed by Application.Current.Dispatcher
).
Before:
public static UIElement CreateUIElement()
{
UIElement element = new UIElement();
//Initialized the UIElement here
return element;
}
This code caused an XamlParseException as it was called in a different thread than the UI thread.
My working solution :
public static UIElement CreateUIElement()
{
UIElement element = null;
Application.Current.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal, new Action(
delegate()
{
element = new UIElement();
// Initialize your UIElement here
}));
return element;
}
More info about the dispatcher can be found here http://tech.pro/tutorial/800/working-with-the-wpf-dispatcher
Good luck