首页 文章

将图像保存在独立存储中生成'Invalid cross-thread access.'

提问于
浏览
1

我在Windows Phone 8工作 . 我正在尝试将多个图像保存到隔离存储 . 但在保存时,就像我的UI被绞死一样 . 可能是“ Deployment.Current.Dispatcher.BeginInvoke ”正在发生这种情况 . 如果我不使用 Deployment.Current.Dispatcher.BeginInvoke ,那么我会在“ var bi = new BitmapImage(); ”行收到 Invalid cross-thread access 错误 .

保存图像的示例代码:

Deployment.Current.Dispatcher.BeginInvoke(() =>
{
    var workingDictionary = new Dictionary<string, Stream>(streamDictionary);
    foreach (var item in workingDictionary)
    {
       var isoStore = IsolatedStorageFile.GetUserStoreForApplication();

       if (isoStore.FileExists(item.Key))
       isoStore.DeleteFile(item.Key);

       using (var writer = new StreamWriter(new IsolatedStorageFileStream(item.Key, FileMode.Create, FileAccess.Write, isoStore)))
       {
          var encoder = new PngEncoder();
          var bi = new BitmapImage();
          bi.SetSource(item.Value);
          var wb = new WriteableBitmap(bi);
          encoder.Encode(wb.ToImage(), writer.BaseStream);

          System.Diagnostics.Debug.WriteLine("saving..." + item.Key);
       }
    }
});

任何帮助将受到高度赞赏 .

3 回答

  • 1

    你的用户界面肯定会冻结这背后的原因 .

    Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
    // This code run on UI thread..
    }
    

    此代码基本上在UI thead上运行其中的代码 .

    只需将内部代码放在其他异步任务中就可以了 .

    private async Task RunInBackgroud()
    {
       await Task.Run(()=>{}); // This is because any async Task does not went to background until
      // it encounter first await. this is just to make the thread in backgound as fast as possible.
    
       // your code for saving files..
      ..
      ..
    }
    

    并将上面的调用作为一个简单的方法调用 . 希望它对你有所帮助 .

    EDIT : - 为什么不把这个位图创建放在Dispatcher代码中 .

    喜欢..

    BitmapImage bi;
        Dispatcher.BeginInvoke(() => {        
        bi = new BitmapImage();
    });
    

    EDIT 2 : - 以下是类似问题的一些参考..

    Creating BitmapImage on background thread WP7

    Invalid cross-thread access

    Invalid cross-thread access issue

  • 0

    我不熟悉Windows手机编程,但这听起来像是一个线程问题 . 在Windows中,两个操作都将在同一个线程上完成 . 这就是为什么UI不能同时更新,而是仅在保存操作之后更新 .

    也许这对Windows Phone来说是一样的?

  • 0

    您无法直接从任何其他线程访问UI线程 . 所以,在Dispatcher.BeginInvoke()中填充您的UI访问代码

    Dispatcher.BeginInvoke(() =>
        {
            foreach (Button i in bts)
               i.Content = "";
        });
    

    或者请通过以下链接:

    http://www.codeproject.com/Articles/368983/Invoking-through-the-Dispatcher-on-Windows-Phone-a

相关问题