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

后端 未结 15 1081
星月不相逢
星月不相逢 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:48

    Those windows async methods have a nifty little method called AsTask(). You can use this to have the method return itself as a task so that you can manually call Wait() on it.

    For example, on a Windows Phone 8 Silverlight application, you can do the following:

    private void DeleteSynchronous(string path)
    {
        StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
        Task t = localFolder.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask();
        t.Wait();
    }
    
    private void FunctionThatNeedsToBeSynchronous()
    {
        // Do some work here
        // ....
    
        // Delete something in storage synchronously
        DeleteSynchronous("pathGoesHere");
    
        // Do other work here 
        // .....
    }
    

    Hope this helps!

提交回复
热议问题