当实现的接口异步时,如何抑制有关“此异步方法缺少'await'运算符并将同步运行的警告?

时间:2019-11-19 21:38:20

标签: c# async-await

这种方法没有使用await!要我做什么?

    public DatabaseHealthCheck(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public async Task<HealthCheckResult> CheckHealthAsync <------THIS WANTS ASNYC (HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        using (SqlConnection connection =
           new SqlConnection(_configuration.GetConnectionString("PwdrsConnectionRoot")))
        {
            try
            {
                connection.Open();
            }
            catch (SqlException)
            {
                return HealthCheckResult.Healthy();
            }
        }

        return HealthCheckResult.Healthy();
    }
}

}

2 个答案:

答案 0 :(得分:1)

理想情况下,您不想删除async关键字,而是使用基础API的异步副本,这样,只要不受CPU限制,您的代码就可以不阻塞。例如,作为mentioned in comments,您可以使用connection.OpenAsync()代替connection.Open()

public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context,
    CancellationToken cancellationToken)
{
    using (SqlConnection connection =
       new SqlConnection(_configuration.GetConnectionString("PwdrsConnectionRoot")))
    {
        try
        {
            await connection.OpenAsync();
        }
        catch (SqlException)
        {
            return HealthCheckResult.Healthy();
        }
    }

    return HealthCheckResult.Healthy();
}

但是,如果您真的只想删除async关键字并保留实现,则需要用{{1}显式包装返回值和异常}:

Task

那应该正确实现该接口,并保留与先前的private HealthCheckResult CheckHealthImpl(HealthCheckContext context, CancellationToken cancellationToken) { using (SqlConnection connection = new SqlConnection(_configuration.GetConnectionString("PwdrsConnectionRoot"))) { try { connection.Open(); } catch (SqlException) { return HealthCheckResult.Healthy(); } } return HealthCheckResult.Healthy(); } public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { try { return Task.FromResult(CheckHealthImpl(context, cancellationToken)); } catch (Exception e) { return Task.FromException(e); } } 函数相同的行为。

答案 1 :(得分:-1)

如果您需要保留async的方法,有两种方法可以解决您的问题:

  1. 最简单的方法是返回带有静态结果的await Task.FromResult(HealthCheckResult.Healthy())

  2. 您还可以禁止在Visual Studio中显示特定类型的警告,如this doc所示。 TLDR:您可以在项目的属性中对其进行更改。

让我知道这是否有帮助!

保重。