c# - Async ThreadContext ID -
update not problem now. didn't realize theadid returned within , outside dispatcher.invoke method different.
from understanding, when using async, awaiting task t1 executed in different thread , code next await wrapped task t2 continuewith of t1. assume threadcontextid different in code below. code below generate same threadcontextid. understanding wrong?
also, why have utilize dispatcher in t1, can update main ui in t2 directly? how threadcontext switch work in async/await? thanks.
update: code in t1 executing in mainthread in vs debug thread view. however, if in main thread, why can't update ui directly? gives me crossthread exception.
async private void asynctask(object sender, routedeventargs e) { outputdialog.text = thread.currentthread.managedthreadid+ environment.newline + outputdialog.text; task t1 = new task( () => { thread.sleep(5000); outputdialog.dispatcher.invoke(() => { outputdialog.text = "task in await" + environment.newline + outputdialog.text; outputdialog.text = thread.currentthread.managedthreadid + environment.newline + outputdialog.text; }); }); t1.start(); await t1; //t2 outputdialog.dispatcher.invoke(() => { outputdialog.text = "continued task after await 1" + environment.newline + outputdialog.text; }); outputdialog.text = "continued task after await 2" + environment.newline + outputdialog.text; outputdialog.text = thread.currentthread.managedthreadid + environment.newline + outputdialog.text; }
xaml code ui
<grid> <stackpanel> <button click="asynctask">execute now</button> <textbox name="outputdialog" background="gray" foreground="yellow" verticalalignment="stretch" horizontalalignment="stretch" verticalcontentalignment="stretch"> </textbox> </stackpanel> </grid>
after await, flow scheduled on calling thread why don't need invoke in t2. if want go on on t1's thread utilize .configureawait(continueoncapturedcontext: false)
c# asynchronous async-await threadcontext
No comments:
Post a Comment