下面的代码(使用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");
}
}
最佳答案
你不能等待 async void
操作你不应该使用 async void
除了异步事件处理程序。
async void
当你滥用它时有几个问题。 async void
中抛出的异常不会被我的常规手段捕获,并且在大多数情况下会使您的应用程序崩溃。
您应该始终使用 async Task
或 async Task<T>
当您期望返回值时。
查看此 MSDN post有关 async
的一些指南/await
.
关于c# - 如何等待异步方法在 C# 中完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34379810/