创建BitmapImage时Windows Phone C#,UnauthorizedAccessException

时间:2013-02-11 06:59:56

标签: multithreading asynchronous windows-phone bitmapimage unauthorizedaccessexcepti

我正在尝试使用异步调用从Internet下载图像:

    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  
        {  
        }  
    }

似乎当断点点击BitmapImage image = new BitmapImage()时,我得到以下异常:

ex = {System.UnauthorizedAccessException:无效的跨线程访问。    在MS.Internal.XcpImports.CheckThread()    在System.Windows.DependencyObject..ctor(UInt32 nativeTypeIndex,IntPtr constructDO)    在System.Windows.Media.Imaging.BitmapImage..ctor()

我还可以尝试摆脱这个错误吗?

1 个答案:

答案 0 :(得分:1)

回调方法在后台线程中运行,而不是在UI线程中运行。不幸的是,BitmapImage只能在UI线程中实例化。如果需要从回调访问UI线程,请尝试以下操作:

Deployment.Current.Dispatcher.BeginInvoke(() =>
   {
      BitmapImage image = new BitmapImage();
      image.SetSource(e.Result);  
      SecondTile.Source = image;  
   });