如何在返回类型为Task的方法中尝试捕获?

Pix*_*aul -1 c# task-parallel-library

我有以下方法(简称为简称):

public Task CreateAsync(TUser user)
{
    using (var connection = new SqlConnection(_connection))
    {
        return Task.FromResult(connection.Execute("CreateUser", param, commandType: CommandType.StoredProcedure));
    }
 }
Run Code Online (Sandbox Code Playgroud)

我想合并一个try-catch block,所以我可以记录任何潜在的Sql错误.

public Task CreateAsync(TUser user)
{
     var result = ???; // what is the return type here?
     try
     {
         result = FromResult(connection.Execute("CreateUser", param, commandType: CommandType.StoredProcedure));
      }
      catch(SqlException sqlEx)
      {
          // log error here
       }

      return result;
}
Run Code Online (Sandbox Code Playgroud)

我想我不确定返回类型Task是什么?

Ami*_*ich 5

您应该使用异步方法而不是Task.FromResult.我假设你正在使用Dapper或某种扩展的框架SqlConnection.我不知道存储过程返回什么.如果返回值无关紧要,则代码应如下所示.

public async Task CreateAsync(TUser user)
{
     try
     {
         await connection.ExecuteAsync("CreateUser", param, commandType: CommandType.StoredProcedure);
     }
     catch(SqlException sqlEx)
     {
         // log error here
     }
}
Run Code Online (Sandbox Code Playgroud)

如果它确实重要(例如bool):

public async Task<bool> CreateAsync(TUser user)
{
     bool result;
     try
     {
        await connection.ExecuteAsync("CreateUser", param, commandType: CommandType.StoredProcedure);
        result = true;
     }
     catch(SqlException sqlEx)
     {
         // log error here
        result = false;
     }

     return result;
}
Run Code Online (Sandbox Code Playgroud)