c# - Why does await not wait? -


this actual code:

    async task getdata()     {         thread.sleep(5000);         console.writeline("step 1");          using (httpclient api = new httpclient())              await api.getasync("http://google.com/").continuewith(                 (gettask) =>                     console.writeline(gettask.result.statuscode);             );          console.writeline("step 2");     }      private void button1_click(object sender, eventargs e)     {         task<task> task = new task<task>(getdata);         task.start();         task.wait();         console.writeline("step 3");     } 

i following output:

step 1 step 3 ok step 2 

why step 3 not come after step 2?

how work in sequence, ie return caller of getdata until in getdata done?

you should mark event handler async

private async task button1_click(object sender, eventargs e) 

and await instead of wait:

private async task button1_click(object sender, eventargs e) {     await getdata();      console.writeline("step 3"); } 

when use async/await pattern, should go way until first method initiated it. otherwise, calling explicitly wait or result, may run deadlock issues. furthermore, calling explicitly methods block executing thread. drop main benefit of using async/await, not blocking executing thread , run on separate thread code , once done resume execution of code stopped.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -