I have a method where I would like to run three queries in parallel. I am trying to use Task Parallel library to do so as shown:
internal static async Task<RequestAppointmentDBMasterObject> GetDAMasterObject(string facility, string sites, string state)
{
RequestAppointmentDBMasterObject mo = new RequestAppointmentDBMasterObject();
string querySites = query1;
string queryPractitioners = query2;
string queryExistingAppts = query3;
using (IDbConnection db = new OdbcConnection(connectionString))
{
await Task.Run(() =>
{
Parallel.Invoke(
() => { mo.SiteList = db.Query<Sites>(querySites).ToList(); },
() => { mo.PractitionerList = db.Query<Practitioners>(queryPractitioners).ToList(); },
() => { mo.ExistingAppointments = db.Query<AvailResponseObject>(queryExistingAppts).ToList(); }
);
});
}
return mo;
}
Then, on another class I am calling this method to set the object I am going to work with as shown below:
RequestAppointmentDBMasterObject mo = DataAccess.GetDAMasterObject(facility, site, state).Result;
The problem is that I never get a result back when I call the API. Once I change everything back to not use the Task and Parallel libs. everything works fine. I also tried this same code in a Console App and I got data back. I am not sure why I might be missing on the code so I can use this on my API. Thank you in advance.
Parallel.Invokedoesn't help at all. Dapper hasQuerryAsyncso there's no reason to callTask.Runto callQuery. Worse,Parallel.Invoke` is modifying shared stateParallel.Invoke. It's the wrong thing to use in the first place. It's wasting threads and prevents you from usingQueryAsyncmo.SiteList = db.QueryAsync<Sites>(querySites).Result.ToList(); mo.PractitionerList = db.QueryAsync<Practitioners>(queryPractitioners).Result.ToList(); mo.ExistingAppointments = db.QueryAsync<AvailResponseObject>(queryExistingAppts).Result.ToList();.Resultblocks. You must useawaitto await completion without blocking. Richard's answer shows this