I want to fetch data from 5 different views of the same database asynchronously - I used the following solution:
public async Task<List<Product>> GetProductsAsync()
{
string query = $"SELECT * FROM dbo.v_Products";
try
{
Stopwatch sw = new Stopwatch();
sw.Start();
var items = await _dbContext.Database.SqlQuery<Product>(query).ToListAsync();
sw.Stop();
Debug.WriteLine("\t " + Thread.CurrentThread.ManagedThreadId + $" getting Products ({items.Count}) seconds: " + sw.Elapsed.TotalSeconds);
return items;
}
catch (Exception ex)
{
throw new Exception("Getting Products failed!", ex);
}
}
There is the following situation: I have ~30 databases, a thread is ran for each one and methods like "GetProductAsync" are executed for gathering data. But I haven' see improvement of using async, it seems that time of execution of each next method contains the time of execution of previous. Where could I be wrong?
UPD: Calling the function
public async Task<DataContext> GetDataAsync()
{
DataContext data = new DataContext();
var items1= await _dac.GetProductsAsync();
var items2 = await _dac.GetProducts2Async();
var items3 = await _dac.GetProducts3Async();
var items4 = await _dac.GetProducts4Async();
var items5 = await _dac.GetProducts5Async();
data.items1= items1;
data.items2= items2;
data.items3= items3;
data.items4= items4;
data.items5= items5;
return data;
}
Is it OK if I will recreate db context for each async method execution, like here?
public async Task<List<Product>> GetProductsAsync()
{
string query = $"SELECT * FROM dbo.v_Products";
var ctx = new myDbContext(_dbContext.Database.ConnectionString);
try
{
Stopwatch sw = new Stopwatch();
sw.Start();
var items = await ctx.Database.SqlQuery<Product>(query).ToListAsync();
sw.Stop();
Debug.WriteLine("\t " + Thread.CurrentThread.ManagedThreadId + $" getting Products ({items.Count}) seconds: " + sw.Elapsed.TotalSeconds);
return items;
}
catch (Exception ex)
{
throw new Exception("Getting Products failed!", ex);
}
}