且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不等待的情况下安全地调用 C# 中的异步方法

更新时间:2022-03-10 23:08:45

如果你想异步"获取异常,你可以这样做:

If you want to get the exception "asynchronously", you could do:

  MyAsyncMethod().
    ContinueWith(t => Console.WriteLine(t.Exception),
        TaskContinuationOptions.OnlyOnFaulted);

这将允许您处理main"线程以外的线程上的异常.线.这意味着您不必等待"从调用 MyAsyncMethod 的线程调用 MyAsyncMethod() ;但是,仍然允许您在异常情况下执行某些操作——但前提是发生异常时.

This will allow you to deal with an exception on a thread other than the "main" thread. This means you don't have to "wait" for the call to MyAsyncMethod() from the thread that calls MyAsyncMethod; but, still allows you to do something with an exception--but only if an exception occurs.

从技术上讲,你可以用 await 做类似的事情:

technically, you could do something similar with await:

try
{
    await MyAsyncMethod().ConfigureAwait(false);
}
catch (Exception ex)
{
    Trace.WriteLine(ex);
}

...如果您需要专门使用 try/catch(或 using),这将很有用,但我发现 ContinueWith 更明确一点,因为您必须知道 ConfigureAwait(false) 表示.

...which would be useful if you needed to specifically use try/catch (or using) but I find the ContinueWith to be a little more explicit because you have to know what ConfigureAwait(false) means.