对于下面的代码(使用EdgeJS模块),我想在编写sw.Elapsed之前等待异步方法Start完成,我应该怎么做?
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");
}
}发布于 2015-12-20 18:06:31
你不能等待async void操作,你也不应该使用async void,除了异步事件处理程序。
当您误用async void时,它有几个问题。在async void中抛出的异常不会被常规方法捕获,并且在大多数情况下会使您的应用程序崩溃。
当您需要返回值时,应始终使用async Task或async Task<T>。
有关async/await的一些指导原则,请参阅此MSDN post。
发布于 2017-10-11 22:59:47
在this question中,您可以使用
sw.Start().GetAwaiter().GetResult;或
Task.WaitAll(sw.Start());分别来自Stephen Cleary和SnOrfus的答案。希望能有所帮助。
发布于 2015-12-20 18:24:20
好吧,问题是所有的东西都源自同步的Main()方法。如果您想要编写异步代码,那么一个好的开始方法是创建一个异步的Main方法,然后在那里编写您的程序代码(i answered a similar question recently)。
class Program
{
static void Main(string[] args)
{
Task mainTask = MainAsync(args);
mainTask.Wait();
// Instead of writing more code here, use the MainAsync-method as your new Main()
}
static async Task MainAsync(string[] args)
{
// Write your programs code here, You can freely use the async / await pattern
}
}再加上允许你的"Start“方法像这样返回一个Task:
public static async Task 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");
}将允许您在MainAsync方法中调用Start方法,如下所示:
static async Task MainAsync(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
await Start();
//wait for start to complete --- how should I do it??
sw.Stop();
Console.WriteLine(sw.Elapsed);
}我无法测试它,因为我不知道这个静态的"Edge“类是从哪里来的。但在我看来,这是一个很好的起点。
https://stackoverflow.com/questions/34379810
复制相似问题