picturebox - Display WPF Image in backgroundworker -
i using wpf 3.5.
i have while loop in backgroundworker_dowork event, continuously stream images dslr.
initially, streamed image displayed in picturebox
<grid> <windowsformshost verticalalignment="top" background="transparent" height="500"> <wf:picturebox x:name="picliveview" /> </windowsformshost> </grid>
here code behind:
while (!liveviewexit) { try { if (picimage != null) lock (mylock) { this.picliveview.image = (image)picimage.clone(); } } catch { } }
this works fine.
however, when try change picturebox wpf image control, have error when assigned bitmapimage wpf image control:
{"the calling thread cannot access object because different thread owns it."}
memorystream ms = new memorystream(); bmp.save(ms, imageformat.png); ms.position = 0; bitmapimage bi = new bitmapimage(); bi.begininit(); bi.streamsource = ms; bi.endinit(); try { if (bi != null) { this.imagebox.source = bi; } } catch { }
why .net 2 picturebox control works while .net 3.5 wpf image control doesn't?
i tried code:
backgroundworker bg = new backgroundworker(); dispatcher disp = dispatcher.currentdispatcher; bg.dowork += (sender, e) => { // load data disp.invoke(new action(/* method or lambda assignment */)); } bg.runworkercompleted += anothermethodorlambda; // optional bg.runworkerasync(/*an argument object visible in e.argument*/);
it doesn't have error, image doesn't refresh. while loop make application not responding.
you need instantiate dispatcher object in main thread, , use in background worker, calling it's invoke method.
here's sample of code:
backgroundworker bg = new backgroundworker(); dispatcher disp = dispatcher.currentdispatcher; bg.dowork += (sender, e) => { // load data disp.invoke(new action(/* method or lambda assignment */)); } bg.runworkercompleted += anothermethodorlambda; // optional bg.runworkerasync(/*an argument object visible in e.argument*/);
Comments
Post a Comment