c# - C# 以异步方式与数据库交互,不起作用。
问题描述
我只是想创建一个虚拟的 ASP.NET MVC 项目,我想在其中探索更多关于 async 和 await 的信息。我在 DB 访问层和存储库层中创建了异步方法,并且我还确保该操作也是以异步方式编写的。我注意到一个方法执行大约需要 7 毫秒,所以从逻辑上讲,如果我调用该方法 3 次,我也应该花费 7 毫秒或大约 7 毫秒!但它大约需要 20-23 毫秒。我确信我在做一些非常错误的事情。我的代码片段如下:
数据访问层:
public async Task<DataTable> DtGetAllCustomers()
{
await Task.Run(() =>
{
_dtCustomer = new DataTable();
_connectionString = Repo.GetConnString();
_spName = "spGetCus";
_spParameters = new SqlParameter[]
{
new SqlParameter("@QryOption",1)
};
using (var conn = new SqlConnection(_connectionString))
{
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = _spName;
cmd.Parameters.AddRange(_spParameters);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(_dtCustomer);
conn.Close();
da.Dispose();
}
}
}
});
return _dtCustomer;
}
存储库:
public async Task<List<CustomerModel>> GetAllCustomers()
{
_dtCustomer = await _customerDal.DtGetAllCustomers();
List<CustomerModel> allCustomers = new List<CustomerModel>();
return allCustomers = (from DataRow row in _dtCustomer.Rows
select new CustomerModel
{
CustomerId = (int)row["CustomerId"],
CustomerName = (string)row["CustomerName"]
}).ToList();
}
行动:
public async Task<ActionResult> Index()
{
var watch = System.Diagnostics.Stopwatch.StartNew();
List<CustomerModel> model = new List<CustomerModel>();
CustomerRepo2 aa = new CustomerRepo2();
await aa.GetAllCustomers();
await aa.GetAllCustomers();
await aa.GetAllCustomers();
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
ViewBag.time = elapsedMs;
return View();
}
解决方案
您正在等待每个调用,因此在它可以移动到下一个之前,它将暂停执行。考虑创建三个任务,并使用以下命令等待它们Task.WhenAll()
:
var task1 = aa.GetAllCustomers();
var task2 = aa.GetAllCustomers();
var task2 = aa.GetAllCustomers();
await Task.WhenAll(task1, task2, task3);
推荐阅读
- php - 如何在遗留系统中测试 json-api 的排序
- oracle11g - PHP 5.2.0-8 上的 oci_connect 不适用于 Oracle 11g
- wagtail - 无法让联合查询在 Wagtail 中的不同模型中工作
- sql-server - 如何修复 SSIS 中缺少的 SQL 连接管理器
- r - 通过数据帧循环函数,区分,然后在原始数据帧中按列组合
- php - 遍历 JSON 请求的多个页面(Guzzle、Laravel、PHP)
- blazor - 当我在表单中选择另一个文本框时,羽毛笔编辑器的内容被清除
- python - 我的代码返回“命令 '['python3']' 2 秒后超时”
- c# - 就地更新 PDF 图像
- javascript - React Native:获取函数发送空主体