How to call asynchronous method from synchronous method in C#?

后端 未结 15 1036
星月不相逢
星月不相逢 2020-11-21 06:27

I have a public async void Foo() method that I want to call from synchronous method. So far all I have seen from MSDN documentation is calling async methods via

15条回答
  •  渐次进展
    2020-11-21 06:47

    public async Task StartMyTask()
    {
        await Foo()
        // code to execute once foo is done
    }
    
    static void Main()
    {
         var myTask = StartMyTask(); // call your method which will return control once it hits await
         // now you can continue executing code here
         string result = myTask.Result; // wait for the task to complete to continue
         // use result
    
    }
    

    You read the 'await' keyword as "start this long running task, then return control to the calling method". Once the long-running task is done, then it executes the code after it. The code after the await is similar to what used to be CallBack methods. The big difference being the logical flow is not interrupted which makes it much easier to write and read.

提交回复
热议问题