I am trying to load an image in the background and then update the UI. I have been playing with this all day and I don't know what I am missing. I keep getting the following error:
"The calling thread cannot access this object because a different thread owns it."
I've hunted around following example after example, but I cannot seem to find an answer. I also wrapped the code that is touching the UI in another BeginInvoke.
Update 3: The moral of the story. ImageSource is not thread safe for access.
Update 2: This has got to be a simple solution :). I tried the cloning, but that didn't result in success, but I did get a different error: "Exception has been thrown by the target of an invocation."
Update 1: I tried the BackgroundWorker, but I am still getting the same error, but it is occurring on the brush.ImageSource.Height. Am I signaling the UI correctly? Any suggestions?
Here is my XAML:
<Window x:Class="Slideshow.Show"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DockPanel>
<Canvas Background="Black" Name="canvas">
<Viewbox Name="background" Stretch="Uniform">
<Rectangle name="background" />
</Viewbox>
</Canvas>
</DockPanel>
</Window>
Here is some of the code behind:
namespace Slideshow
{
public class Show
{
public Show()
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
BitmapSource bitmap = e.Result as BitmapSource;
if (bitmap != null)
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal
(ThreadStart)delegate()
{
Image image = new Image();
image.Source = bitmap;
background.Child = image;
});
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
BitmapSource bitmapSource = CreateBrush(GetRandomFile());
e.Result = bitmapSource;
}
}
}
You want to incorporate multiple threads in your WPF application. As stated in the article below, WPF forces you to do all UI work on the thread that created the UI.
Check this out: http://pjbelfield.wordpress.com/2007/10/29/worker-threads-and-the-dispatcher-in-wpf/
and for intensive UI work:
http://eprystupa.wordpress.com/2008/07/28/running-wpf-application-with-multiple-ui-threads/
One more thing we had in our project. Since ImageSource is placed into UI you have to check if it is frozen:
Your code to load the image (.jpg) into memory should be done in the background. Code to load the image from memory into a WPF control must be done in the normal UI WPF thread. Only slow/long running tasks should be put into a background thread. Once the long task is complete, it must signal the UI thread to update the view with the result of the long task.
My favourite way is using the BackgroundWorker class:
When you call RunWorkerAsync(), first your Work_Function() is called. When it is complete, the UI_Function() is called. The work function may place one variable in the DoWorkEventArgs.Result property, which is accessible from the RunWorkerCompletedEventArgs.Result property.
I think you might also be interested in this article: http://www.codeproject.com/KB/WPF/WPF_Explorer_Tree.aspx It shows how to set up Lazy Loading in a tree view in WPF. I think the basic concept (add a dummy node, intercept the display of the dummy node by loading the next image instead) will apply to your work.
What I tend to use the
ThreadPool.QueueUserWorkItem
to load the image, then when the operation completes I call back to the UI thread using the thread-safeDispatcher
object. The image source is not thread safe, you will have to use something like theJpegBitmapDecoder
, there is also aPngBitmapDecoder
.For Example:
The error you are getting now is good news, it means that
BackgroundWorker
is working. You could try cloning it in theRunWorkerCompleted
withbrush.Clone();
.Try removing the Dispatcher.BeingInvoke part. The whole point of BackgroundWorker is that the event is marshaled back into the UI thread for you automatically so you don't have to worry.