c# - The calling thread cannot access this object because a different thread owns it (async/await/task) -


i'm moving long running code background using async/await etc, hitting subject-line error. i'm aware cannot update wpf ui controls task (and i've added dispatcher appropriately) error occurs updating object in class. example:

private writeablebitmap tempimage;  public async void startprocessing() {    writeablebitmap loadedimage =  new writeablebitmap(await loadimage(0)); //error here    loadedimage.freeze();    tempimage = loadedimage;    // 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 current attempt resolve it, still occurs try assign returned image class-level variable. i'm assuming because ui thread instantiated class, , variable in ui thread context, not sure how resolve it?

you may have freeze bitmapimage created in loadimage. moreover, should close filestream after loading image. therefore need set 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(); // , here     return img; } 

Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -