[英]The calling thread cannot access this object because a different thread owns it (async/await/task)
I'm moving some long running code to background using async/await etc, but hitting the subject-line error. 我正在使用async / await等将一些长时间运行的代码移至后台,但遇到了主题行错误。 I'm well aware I cannot update my WPF UI Controls from the task (and I've added dispatcher appropriately) but this error occurs simply updating an object in my class. 我知道我无法从任务中更新我的WPF UI控件(并且我已经适当地添加了调度程序),但是仅在更新类中的对象时就会发生此错误。 Example: 例:
private WriteableBitmap TempImage;
public async void StartProcessing()
{
WriteableBitmap LoadedImage = new WriteableBitmap(await LoadImage(0)); //ERROR HERE
LoadedImage.Freeze();
TempImage = LoadedImage;
// do more stuff
}
private Task<BitmapImage> LoadImage(int imageIndex)
{
return Task.Run(() =>
{
FileStream fileStream = new FileStream(fileList[0], FileMode.Open, FileAccess.Read);
var img = new BitmapImage();
img.BeginInit();
img.StreamSource = fileStream;
img.EndInit();
return img;
});
}
The "freeze" stuff is my current attempt to resolve it, but it still occurs as soon as I try to assign the returned image to my class-level variable. 我目前试图解决“冻结”问题,但是当我尝试将返回的图像分配给我的类级变量时,它仍然会发生。 I'm assuming this is because my UI thread instantiated the class, and thus the variable is in the UI thread context, but not sure how to resolve it? 我假设这是因为我的UI线程实例化了该类,因此该变量位于UI线程上下文中,但不确定如何解决它?
You may also have to freeze the BitmapImage created in LoadImage. 您可能还必须冻结在LoadImage中创建的BitmapImage。 Moreover, you should also close the FileStream after loading the image. 此外,您还应该在加载图像后关闭FileStream。 Therefore you need to set the BitmapCacheOption.OnLoad
flag. 因此,您需要设置BitmapCacheOption.OnLoad
标志。
using (var fileStream = new FileStream(fileList[0], FileMode.Open, FileAccess.Read))
{
var img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad; // here
img.StreamSource = fileStream;
img.EndInit();
img.Freeze(); // and here
return img;
}
您可以使用Dispatcher
将访问WriteableBitmap
的调用编组到创建它的线程上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.