How to wait for async method to finish in C#?

william007 picture william007 · Dec 20, 2015 · Viewed 14.8k times · Source

For the following code (using EdgeJS module), I want to wait for asynchronous method Start to complete before writing sw.Elapsed, how should I do it?

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using EdgeJs;
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    /// 
    [STAThread]
    static  void Main()
    {
        //            Application.EnableVisualStyles();
        //            Application.SetCompatibleTextRenderingDefault(false);
        //            Application.Run(new Form1());

        Stopwatch sw =new Stopwatch();
        sw.Start();
        Task.Run((Action)Start).Wait();
        //wait for start to complete --- how should I do it??
        sw.Stop();
        Console.WriteLine(sw.Elapsed);
    }


    public static async void Start()
    {
        var func = Edge.Func(@"
        var esprima = require('esprima');
        var stringify = require('json-stable-stringify');

        var esprimaast = esprima.parse('var a=1;', { loc: true });
        var esprimaStr = stringify(esprimaast, { space: 3 });
        return function (data, callback) {
            callback(null, 'Node.js welcomes ' + esprimaStr);
        }
    ");

        Console.WriteLine(await func(".NET"));
        //Console.WriteLine("hello");
    }
}

Answer

Tseng picture Tseng · Dec 20, 2015

You can't await async void operations neither you should use async void except for async event handlers.

async void has several issues when you misuse it. exceptions thrown inside an async void won't be caught my regular means and will in most cases crash your application.

You should always use async Task or async Task<T> when you expect a return value.

See this MSDN post for a few guidelines with async/await.