Async modifier in C#

前端 未结 3 450
逝去的感伤
逝去的感伤 2021-01-01 15:10

I have the question, what is the difference between these two methods?

    async private void Button_Click_1(object sender, RoutedEventArgs e)
    {
                 


        
相关标签:
3条回答
  • 2021-01-01 15:14

    1) The Async key work makes the method asynchrounous with no blocking, by time slicing. Async must exist with await, that tell to wait for the completion of the task, but all the stuff before will be executed.

    async private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var task = Task.Delay(1000);
    
        /*Do stuff*/
    
        await task;
    }
    

    2) Just make a thread sleep only, any code above will not execute, only after the thread sleep finish the task.

    private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        Thread.Sleep(2000);
        /*Do stuff*/
    }
    

    Theres a good read at msdn Asynchronous Programming with Async and Await!

    0 讨论(0)
  • 2021-01-01 15:22

    Adding async, by itself, does nothing other than allow the method body to use the await keyword. A properly implemented async method won't block the UI thread, but an improperly implemented one most certainly can.

    What you probably wanted to do was this:

    async private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        await Task.Delay(2000);
        MessageBox.Show("All done!");
    }
    
    0 讨论(0)
  • 2021-01-01 15:31

    async by itself will not enable asynchronous (non-blocking) method invocation.
    You should use await inside the async function.

    You should read this to have a better understanding of this capability.

    0 讨论(0)
提交回复
热议问题