I just wanted to create a dummy ASP.NET MVC project where i wanted to explore more about async & await.I created async methods in DB access Layer and Repository Layer and i also make sure that the action is also written in async way. I noticed that a single method takes around 7ms to execute, so logically if i call the method 3 times i also should take 7 ms or around 7ms ! But its taking about 20-23 ms. I am sure that i am doing something terribly wrong. My Code snippet goes below:
DATA ACCESS LAYER:
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;
}
REPOSITORY:
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();
}
ACTION:
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();
}
awaitwill execute them in parallel? Parallel programming and asynchronous programming are different concepts. You should get familiar with the theory before writing codeTask.Runis considered a bad practice. Moreover, creating Thread Pool threads to do I/O operations is a waste of processing power. Look at this answer to see how you can do that query in a truly asynchronous way