如何捕获异步void方法异常? [英] How to catch async void method exception?

查看:168
本文介绍了如何捕获异步void方法异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的实现:

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
    }
}

问题是无效的匿名方法async () => ParseItemsFromResponse(..).

The issue is the void anonymous method async () => ParseItemsFromResponse(..).

由于它返回void而不是Task,因此,如果在匿名方法中引发异常,则实际上不会被RunRequest中的trycatch捕获.

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.

有什么建议可以重构吗?

Any suggestions how to refactor this?

推荐答案

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
  }
}

然后将您的async lambda转换为async Task<T>方法而不是async void.

Then your async lambdas are converted to async Task<T> methods instead of async void.

我有关于同步/异步委托的更多信息

这篇关于如何捕获异步void方法异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆