我当前正在调用异步
方法,并且不想等待
它。我不需要 async 方法的结果,并且不想在 IO 期间阻塞。但是,如果async
方法中抛出错误,我想catch
它。到目前为止我已经:
public static void main () {
MyAsyncMethod().
ContinueWith(t => Console.WriteLine(t.Exception),
TaskContinuationOptions.OnlyOnFaulted);
//dostuff without waiting for result
}
这不会捕获 Main
中的 MyAyncMethod
中引发的异常。我做错了什么吗?
最佳答案
async-await 和 ContinueWith
可以工作,但充满了麻烦。只需将错误处理重构为一个方法并将其放入其中,然后您就可以从主方法中调用该新方法,这样会容易得多。
public static void main () {
var task = DoMyAsyncMethod();
//dostuff without waiting for result
//Do a wait at the end to prevent the program from closing before the background work completes.
task.Wait();
}
private static async Task DoMyAsyncMethod()
{
try
{
await MyAsyncMethod();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
我怀疑您正在处理的真正问题是缺少 Wait()
并且您的程序在后台工作完成处理之前自行关闭。
关于.net - 调用异步方法而不等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33355656/