.net - await in WPF doesn't return to UI Thread -


i have strange behavior in wpf 4.5 (.net 4.5). i'm using keywords await , async in order run long-operations (for example load big bitmapimage, base image control). problem awaiter doesn't return main ui thread, because teh famous exception:

the calling thread cannot access object because different thread owns it.

could me?

here code:

event handler of button:

    private void getexifdata_click(object sender, routedeventargs e)     {         // async method         (new analyzesingleimage()).runexif(this);                } 

the main method (in separate class, same assembly)

    public async void runexif(mainwindow win)     {       // here run correctly code on main ui thread       ..       ..       // async !!!       bitmapimage bi = await loadimageasync(filename);        image img = new image();       img.source = bi;  // *********** here exception *************       ..       ..     } 

the async method:

    private task<bitmapimage> loadimageasync(string filename)     {         return task<bitmapimage>.run(() => loadimage(filename));     } 

the long time method:

    private bitmapimage loadimage(string filename)     {         bitmapimage bi = new bitmapimage();         bi.begininit();         bi.urisource = new uri(filename);         bi.cacheoption = bitmapcacheoption.onload;         bi.endinit();          return bi;     } 

someone me please?

loadimage runs on thread-pool because pushed there using task.run. valid use ui elements on different threads must access them on same thread consistently.

the bitmapimage created bound thread-pool thread. cannot combined main ui.

for reason, best practice have ui on single thread. create bitmap on main thread.

if remember wpf correctly creating bitmapimage quick , loading image async anyway.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -