首页 > 解决方案 > 使 WebApi 方法异步 - 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 个),所以我想有必要使方法异步。

如何使控制器动作异步运行?

提前致谢。

标签: c#.netasp.net-web-api2

解决方案


为了使其真正异步,您需要做几件事:

  1. 将方法的返回类型更改为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);
}

推荐阅读