首页 > 解决方案 > 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();
        }

标签: c#asp.net-mvcasync-await

解决方案


您正在等待每个调用,因此在它可以移动到下一个之前,它将暂停执行。考虑创建三个任务,并使用以下命令等待它们Task.WhenAll()

var task1 = aa.GetAllCustomers();
var task2 = aa.GetAllCustomers();
var task2 = aa.GetAllCustomers();
await Task.WhenAll(task1, task2, task3);

推荐阅读