I am trying to download image from Internet using async call like this:

    private void DoGetAlbumart(object sender, DoWorkEventArgs e)
    {
        string req = (string)e.Argument;
        WebClient wc = new WebClient();
        wc.OpenReadCompleted += new OpenReadCompletedEventHandler(ReadWebRequestCallback);
        wc.OpenReadAsync(new Uri(req)); 

    }

    void ReadWebRequestCallback( object sender, OpenReadCompletedEventArgs e)
    {
        if (e.Error == null && !e.Cancelled)  
        {  
            try  
            {  
                BitmapImage image = new BitmapImage();  
                image.SetSource(e.Result);  
                SecondTile.Source = image;  
            }  
            catch (Exception ex)  
            {  
            }  
        }  
        else  
        {  
        }  
    }

It seems that when breakpoint hits at BitmapImage image = new BitmapImage(), I got the following exception:

ex = {System.UnauthorizedAccessException: Invalid cross-thread access. at MS.Internal.XcpImports.CheckThread() at System.Windows.DependencyObject..ctor(UInt32 nativeTypeIndex, IntPtr constructDO) at System.Windows.Media.Imaging.BitmapImage..ctor()

What else can I try to get rid of this error?

有帮助吗?

解决方案

Callback methods run in background threads, not the UI thread. Unfortunately, BitmapImages can only be instantiated in the UI thread. If you need to access the UI thread from a callback, try the following:

Deployment.Current.Dispatcher.BeginInvoke(() =>
   {
      BitmapImage image = new BitmapImage();
      image.SetSource(e.Result);  
      SecondTile.Source = image;  
   });
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top