c# - 使 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 个),所以我想有必要使方法异步。
如何使控制器动作异步运行?
提前致谢。
解决方案
为了使其真正异步,您需要做几件事:
- 将方法的返回类型更改为
Task<HttpResponseMessage>
async
用关键字标记它,以便您可以异步等待(await
)其中的其他任务- 使用异步版本的方法打开数据库连接和查询执行
所以,重构之后,方法应该是这样的:
[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);
}
推荐阅读
- node.js - GitHub 显示子模块而不是子文件夹
- vue.js - 无法读取未定义的属性“长度” - 为什么 DOM 在“创建”之前尝试加载?
- python - 尝试点击亚马逊畅销书排名(Python)
- python - Seaborn displot - 在一个图中绘制多个图
- python - 如何将 OTP 发送到 Django 中的电话号码?
- python-3.x - 向数据框熊猫添加行
- php - 如何从 PHP 上的 $_GET 值向数据库表中插入数据
- html - 在带有 Python3 的树莓中为 arduino 使用 HTML
- c# - While/for 循环直到出现特定条件
- c# - 从 NET Core Web 应用程序调用 Microsoft Graph SDK 时出现 MsalUiRequiredException