ThreadPool和Dispatcher共享Stream? [英] ThreadPool and Dispatcher sharing Stream?

查看:122
本文介绍了ThreadPool和Dispatcher共享Stream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做:

 使用( var  albm = isoStore.CreateFile(  shared/media/" + dlSongInfo.id +  -NP"))
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(()= > 
                             {
                                 BitmapImage图片=  BitmapImage();
                                 image.SetSource(e.Result);
                                 WriteableBitmap wb =  WriteableBitmap(image);

                                 wb.SaveJpeg(albm, 358  358  0  100 );
                             });
                        } 



但是它说在执行SaveJpeg时流是关闭的.我猜是因为在不同的线程中它无法访问它?我该如何做到这一点.还是在不需要使用UI线程的情况下从流写入位图图像的另一种方法?

P.S.这是在ThreadPool上执行的.在单核计算机上,您可能会在这里看到竞赛,因为有时它可以工作,但大多数情况下是不会的.只需不将所有这些内容放在using语句中,而是正常创建albm对象并将其放置在您要调用的委托中.

  var  albm = isoStore.CreateFile("  + dlSongInfo.id + "  ));
Deployment.Current.Dispatcher.BeginInvoke(()= >  {
  尝试 {
    BitmapImage图片=  BitmapImage();
    image.SetSource(e.Result);
    WriteableBitmap wb =  WriteableBitmap(image);
    wb.SaveJpeg(albm, 358  358  0  100 );
  } 最终 {
    albm.Dispose();
  }
}); 


Im trying to do this:

using (var albm = isoStore.CreateFile("shared/media/" + dlSongInfo.id + "-NP"))
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                             {
                                 BitmapImage image = new BitmapImage();
                                 image.SetSource(e.Result);
                                 WriteableBitmap wb = new WriteableBitmap(image);

                                 wb.SaveJpeg(albm, 358, 358, 0, 100);
                             });
                        }



But it said that the stream is closed when doing the SaveJpeg. I guess that because there in different threads it can''t access it? How can I achieve this. Or is is an alternative way of writing a bitmap image from a stream without needing to use a UI thread?

P.S. This is execute on a ThreadPool.

解决方案

The using statement disposes your object before (in most cases) your Delegate gets executed. On single core machines you could see a race here, because sometimes it could work but mostly it won''t. Simply don''t put all this in a using statement but instead create the albm object normally and dispose it in the delegate you''re calling.

var albm = isoStore.CreateFile("shared/media/" + dlSongInfo.id + "-NP"));
Deployment.Current.Dispatcher.BeginInvoke(() => {
  try {
    BitmapImage image = new BitmapImage();
    image.SetSource(e.Result);
    WriteableBitmap wb = new WriteableBitmap(image);
    wb.SaveJpeg(albm, 358, 358, 0, 100);
  } finally {
    albm.Dispose();
  }
});


这篇关于ThreadPool和Dispatcher共享Stream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆