如何在 C# 中等待异步方法完成?

wil*_*007 5 c# asynchronous edgejs

对于下面的代码(使用EdgeJS模块),我想等待异步方法Start完成后再写sw.Elapsed,我该怎么做?

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

Tse*_*eng 4

除了异步事件处理程序之外,您不能等待async void操作,也不应该使用这些操作。async void

async void当你滥用它时会出现几个问题。async void我的常规方法不会捕获内部抛出的异常,并且在大多数情况下会导致您的应用程序崩溃。

当您期望返回值时,您应该始终使用async Taskor 。async Task<T>

有关/的一些指南,请参阅此MSDN 帖子asyncawait