简体   繁体   English

如何捕获异步void方法异常?

[英]How to catch async void method exception?

I have an implementation like this: 我有一个这样的实现:

Task<IEnumerable<Item1>> GetItems1() 
{
    return RunRequest(async () => ParseItemsFromResponse(await(httpClient.Get(..))));
}

Task<IEnumerable<Item2>> GetItems2() 
{
    return RunRequest(async () => ParseItemsFromResponse(await httpClient.Get(..)));
}


TResult RunRequest<TResult>(Func<TResult> req)
{
    try
    {
        return req();
    }
    catch (Exception ex)
    {
        // Parse exception here and throw custom exceptions
    }
}

The issue is the void anonymous method async () => ParseItemsFromResponse(..) . 问题是无效的匿名方法async () => ParseItemsFromResponse(..)

Since it returns void and not a Task , if there's an exception thrown within the anonymous method, it's actually not going to be caught by the try and catch within the RunRequest . 因为它返回void而不是Task ,所以如果在匿名方法中引发异常,则实际上不会被RunRequesttrycatch

Any suggestions how to refactor this? 有什么建议如何重构吗?

RunRequest should take a Func<Task<TResult>> , as such: RunRequest应该采用Func<Task<TResult>> ,例如:

async Task<TResult> RunRequestAsync<TResult>(Func<Task<TResult>> req)
{
  try
  {
    return await req().ConfigureAwait(false);
  }
  catch (Exception ex)
  {
    // Parse exception here and throw custom exceptions
  }
}

Then your async lambdas are converted to async Task<T> methods instead of async void . 然后将您的async lambda转换为async Task<T>方法,而不是async void

I have more information on sync/async delegates on my blog. 我在博客上有关于同步/异步委托的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM