[英]How to connect with database and return values using Async/await task in Web Api controller c#
Hello i am trying to connect with database and return values from a web api controller.I want to do it all the way asynchronous with new task to have better performance if it is possible.here is an example of what i have done.Am i doing it the correct way?Am i using correct the using statements?is the await correct in Open,Close connection and sda.FillAsync ?Thanks! 您好我正在尝试与数据库连接并从Web api控制器返回值。我想一直与新任务异步进行,以尽可能获得更好的性能。这是我所做的一个示例。我正确的方法吗?我使用正确的using语句吗?打开,关闭连接和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 });
}
Replace 更换
return await Task.Run(() => GetAllCustomers());
with 同
return await GetAllCustomers();
You don't need to run the service task explicitly (the controller method is already marked as async
). 您无需显式运行服务任务(控制器方法已标记为
async
)。
Rename GetAllCustomers
to GetAllCustomersAsync
(best-practice naming convention) 将
GetAllCustomers
重命名为GetAllCustomersAsync
(最佳做法命名约定)
I prefer to code WebApis this way: 我更喜欢这样编写WebApis:
public async Task<IHttpActionResult> Get()
{
try
{
var result = await GetAllCustomersAsync();
return Ok(result);
}
catch(Exception ex)
{
return InternalServerError(ex);
}
}
UPDATE : An update to show how your database-operation can be simplified: UPDATE :显示如何简化数据库操作的更新:
private async Task<Customers> GetAllCustomersAsync()
{
var customers = new DataTable();
using (var con = new MySqlConnection(""))
using (var cmd = new MySqlCommand("SELECT * FROM Customers", con))
{
await con.OpenAsync();
cmd.CommandType = CommandType.Text;
var sda = new MySqlDataAdapter(cmd);
await sda.FillAsync(customers);
}
return customers;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.