Clearly, there is something I am not understandig with async/await.
What is wrong with the following code? It creates the FDecoder
object in an async task. But after that, whenever I try to access the FDecoder field I get an InvalidOperation exception stating that the object is owned by another thread. I thought that's the cool thing about await, that i get the results back into the calling thread...?
//could take very long for image from web
private Task<GifBitmapDecoder> OpenFileTask(string filename, bool forceReload = false)
{
return Task.Run(() =>
{
return new GifBitmapDecoder(new Uri(filename, UriKind.RelativeOrAbsolute), forceReload ? BitmapCreateOptions.IgnoreImageCache : BitmapCreateOptions.None, BitmapCacheOption.Default);
});
}
GifBitmapDecoder FDecoder;
public async void OpenFileAsync(string filename, bool forceReload = false)
{
FDecoder = await OpenFileTask(filename, forceReload);
OpenCompleted(); // do stuff with FDecoder field, throws invalid thread exception
}
EDIT:
Ok, what i found out is that the actual GifBitmapDecoder object the Task creates is a DispatcherObject which has thread affinity. This is the main problem... It appears that the only way is to get all needed data out of the Dispatcher object in the async task and pass back a normal object without thread affinity. But if anyone knows a better method, please tell me.