문제

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