I'm so frustrated trying to solve this. Why is creating threads and updating UI after completing them so complicated?! I have tried this, this and this and I still can't get my head around the whole multi-threading thing clearly at all. It was so easy in Java...
Anyway here's a simplified version of my code as the result of third link:
private delegate void SimpleDelegate2(BitmapImage bi);
private delegate void SimpleDelegate(string st1, string st2);
private void Process(string st1)
{
try
{
string st2 = "test st2";
SimpleDelegate del = new SimpleDelegate(LongRunningProcess);
del.BeginInvoke(st1, st2, null, null);
}
catch
{
//do some failsafe thing
}
}
private void LongRunningProcess(string st1, string st2)
{
//do some long processing with the strings
BitmapImage bi = new BitmapImage();//there will be an actual bitmap here
SimpleDelegate2 del1 = delegate(BitmapImage bimg)
{
ImageControlOnWPFform.Source = bimg; //null;
};
this.Dispatcher.BeginInvoke(DispatcherPriority.Send, del1, bi);
}
The problem here is that I can't set the Source
value of the Image control to bimg
but I can set it to null
! Whenever I try to set it to bimg
I get the exception that says the calling thread cannot access this object because a different thread owns it. I have also tried setting it directly to bi
which also gives the same exception.
But I can set the source to null
without any problem, which means I can modify the Source
value of the Image control. But how do I access bi
or bimg
? Am I doing something wrong?
Also: I notice that the given arguments of the last BeginInvoke
do not match any overload of the method but they are still accepted as valid and works properly. When I point at BeginInvoke
I am shown a completely different set of method overloads than the ones that appear when I type a (
following the method name. Why?