使 WebApi 方法异步 - ASP.NET

Making WebApi method asynchronous - ASP.NET

我的 Web Api 控制器中有以下操作:

[HttpPost]
[Route("api/geom")]
public HttpResponseMessage AddRef([FromBody]Peticion empObj)
{
    using (SqlConnection con = new SqlConnection("Server=xx;database=xx;User Id=xx;Password=xx"))
    {
        string query = "UPDATE [dbo].[tmp_parcelas] SET[geom] = geometry::STGeomFromText('" + empObj.geom + "',25830) WHERE[idparcela] = " + empObj.id + ";";
        using (SqlCommand querySaveStaff = new SqlCommand(query))
        {
            querySaveStaff.Connection = con;
            con.Open();
            querySaveStaff.ExecuteNonQuery();
            con.Close();
        }
    }
    return Request.CreateResponse(HttpStatusCode.OK);
}

它在很短的时间内收到了很多请求(比如 1 秒左右 60 个),所以我想有必要使该方法异步。

How can I make the controller action run asynchronously?

提前致谢。

为了让它真正异步,你需要做几件事:

  1. 将方法的 return 类型更改为 Task<HttpResponseMessage>
  2. async 关键字标记它,这样您就可以异步等待 (await) 它里面的其他任务
  3. 使用异步版本的方法打开数据库连接和执行查询

因此,重构后,方法应如下所示:

[HttpPost]
[Route("api/geom")]
public async Task<HttpResponseMessage> AddRef([FromBody]Peticion empObj)
{
    using (SqlConnection con = new SqlConnection("connection-string"))
    {
        string query = "query";
        using (SqlCommand querySaveStaff = new SqlCommand(query))
        {
            querySaveStaff.Connection = con;
            await con.OpenAsync();
            await querySaveStaff.ExecuteNonQueryAsync();
            con.Close(); // in this case not needed will be closed when disposed
        }
    }
    return Request.CreateResponse(HttpStatusCode.OK);
}