2

i'm learning c# and wpf. i tried to load a img from net and bind it to a Image,but failed.

it says "The calling thread cannot access this object because a different thread owns it"

but i already used "Img1.Dispatcher.Invoke()",why it casue this exception again?

private void Window_ContentRendered(object sender, EventArgs e)
{
    Img1.Dispatcher.Invoke(async () =>
    {
         Img1.Source = await DownloadImg("http address");
    });
}

private Task<ImageSource> DownloadImg(string url)
{
     return Task.Run(() =>
     {
         ImageSource source = new BitmapImage(new Uri(url));
         return source;
     });
}
Elan.Cao
  • 75
  • 10
  • 1
    From the answer to the duplicate question, you may replace BitmapFrame by BitmapImage. The important thing is to first asynchronously download the image buffer, and then create and return a frozen BitmapSource. – Clemens Mar 21 '17 at 11:50

1 Answers1

2

You can't access the Image because you have to do this in the UI thread. You can make a private field and in your constructor you set this with _dispatcher = Dispatcher.CurrentDispatcher. In your Task you have to use this dispatcher and call the method Invoke to set your Image. More info: Dispatcher.CurrentDispatcher

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51