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 async methods, but my whole program is not built with async methods.
Is this even possible?
Here's one example of calling these methods from an asynchronous method: http://msdn.microsoft.com/en-us/library/hh300224(v=vs.110).aspx
Now I'm looking into calling these async methods from sync methods.
async Main is now part of C# 7.2 and can be enabled in the projects advanced build settings.
For C# < 7.2, the correct way is:
Microsoft built an AsyncHelper (internal) class to run Async as Sync. The source looks like:
The Microsoft.AspNet.Identity base classes only have Async methods and in order to call them as Sync there are classes with extension methods that look like (example usage):
For those concerned about the licensing terms of code, here is a link to very similar code (just adds support for culture on the thread) that has comments to indicate that it is MIT Licensed by Microsoft. https://github.com/aspnet/AspNetIdentity/blob/master/src/Microsoft.AspNet.Identity.Core/AsyncHelper.cs
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.
Or use this:
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:
Hope this helps!
I'm not 100% sure, but I believe the technique described in this blog should work in many circumstances: