将图像保存在独立存储中会生成“无效的跨线程访问”。

时间:2014-10-15 10:22:28

标签: c# image xaml windows-phone-8 isolatedstorage

我正在使用Windows Phone 8.我正在尝试将多个图像保存到隔离存储中。但在保存时,就像我的UI被绞死一样。可能是“ Deployment.Current.Dispatcher.BeginInvoke ”正在发生这种情况。如果我不使用 Deployment.Current.Dispatcher.BeginInvoke ,那么我会在“ var bi = new BitmapImage”行中收到无效的跨线程访问错误);

保存图片的示例代码:

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 个答案:

答案 0 :(得分: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..
  ..
  ..
}

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

编辑: - 为什么不把这个位图创建放在Dispatcher代码中。

像..

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

编辑2 : - 以下是类似问题的一些参考。

Creating BitmapImage on background thread WP7

Invalid cross-thread access

Invalid cross-thread access issue

答案 1 :(得分:0)

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

对于Windows Phone,这可能是相同的吗?

答案 2 :(得分: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