【发布时间】:2018-02-10 10:16:33
【问题描述】:
您好,我正在尝试连接数据库并从 Web api 控制器返回值。如果可能的话,我想一直与新任务异步执行以获得更好的性能。这是我所做的一个示例.我这样做的方式是否正确?我是否使用正确的 using 语句?在 Open、Close 连接和 sda.FillAsync 中的等待是否正确?谢谢!
public async Task<HttpResponseMessage> Get()
{
return await Task.Run(() => GetAllCustomers());
}
private async Task <HttpResponseMessage> GetAllCustomers()
{
DataTable Customers= new DataTable();
using (MySqlConnection con = new MySqlConnection(""))
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customers", con))
{
try
{
if (con.State == ConnectionState.Closed)
{
await con.OpenAsync();
cmd.CommandType = CommandType.Text;
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
await sda.FillAsync(Customers);
}
}
catch (MySqlException ex)
{
ex.Message.ToString();
}
finally
{
await con.CloseAsync();
}
}
return ControllerContext.Request
.CreateResponse(HttpStatusCode.OK, new { Customers });
}
【问题讨论】:
-
更适合CodeReview?
-
public async Task<HttpResponseMessage> Get()AFAIK,建议调用该方法GetAsync。 -
我感觉在 Get() 中不需要明确调用 Task.Run
-
catch (MySqlException ex) { ex.Message.ToString();- 这完全没用。至少记录一下。但最好返回一个错误响应。 -
我投票结束这个问题,因为它是一个代码审查请求。
标签: c# mysql asynchronous asp.net-web-api task