Async modifier in C#

前端 未结 3 449
逝去的感伤
逝去的感伤 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!

提交回复
热议问题