i reading async/await
keywords , i've read that:
when flow of logic reaches await token, calling thread suspended until call completes.
well, i've created simple windows forms application
, placed 2 labels, button , textbox , wrote code:
private async void button1_click(object sender, eventargs e) { label1.text = thread.currentthread.threadstate.tostring(); button1.text = await dowork(); label2.text = thread.currentthread.threadstate.tostring(); } private task<string> dowork() { return task.run(() => { thread.sleep(10000); return "done work"; }); }
what don't understand when click button, label1 have text running
, label have same text after 10 seconds, in these 10 seconds able enter text in textbox, seems main thread running...
so, how async/await works?
regards
i've read that: when flow of logic reaches await token, calling thread suspended until call completes.
where did read nonsense? either there context there you're not quoting, or should stop reading whatever text contained this. point of await opposite of that. point of await to keep current thread doing useful work while asynchronous task in flight.
update: downloaded book referenced. absolutely in section wrong. throw book away , buy better book.
what don't understand when click button, label1 have text running , label have same text after 10 seconds, in these 10 seconds able enter text in textbox, seems main thread running...
that's correct. here's happens:
label1.text = thread.currentthread.threadstate.tostring();
the text set.
button1.text = await dowork();
a bunch of stuff happens here. happens first? dowork
called. do?
return task.run(() => { thread.sleep(10000);
it grabs thread out of thread pool, puts thread sleep ten seconds, , returns task representing "work" being done thread.
now here:
button1.text = await dowork();
we have task in hand. await first checks task see if complete. not. next signs remainder of method continuation of task. returns caller.
hey, caller? how did here anyways?
some code called event handler; event loop processing windows messages. saw button clicked , dispatched click handler, has returned.
now happens? event loop keeps running. ui keeps on running nicely, noticed. thread ticks off ten seconds , task's continuation activated. do?
that posts message windows queue saying "you need run rest of event handler now; have result looking for."
the main thread event loop gets message. event handler picks left off:
button1.text = await dowork();
the await extracts result task, stores in button text, , returns event loop.