调用线程不能访问此对象,因为不同的线程拥有它(异步/计谋/任务) [英] The calling thread cannot access this object because a different thread owns it (async/await/task)
问题描述
我把一些长时间运行的code到后台使用异步/计谋等,但打的主题行错误。我很清楚我不能更新我的WPF UI从任务控制(和我适当地增加调度员),但出现此错误时只需更新我的类的对象。例如:
I'm moving some long running code to background using async/await etc, but hitting the subject-line error. 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. 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;
});
}
冻结的东西是我目前试图解决它,但它仍然当我试图返回的图像分配给我的类级变量发生。我假设这是因为我的UI线程实例化的类,因此变量是在UI线程上下文,但不知道如何解决它?
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?
推荐答案
您可能还需要冻结的LoadImage创建的BitmapImage的。此外,你也应该在加载图像后关闭的FileStream。因此,你需要设置 BitmapCacheOption.OnLoad
标记。
You may also have to freeze the BitmapImage created in LoadImage. Moreover, you should also close the FileStream after loading the image. Therefore you need to set the BitmapCacheOption.OnLoad
flag.
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;
}
这篇关于调用线程不能访问此对象,因为不同的线程拥有它(异步/计谋/任务)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!