Why is Task.Run required here?

Viewed 85

I have an API call from a web app that uses Dapper to query some results and return them back to the user. However, why does this work asynchronously

IEnumerable<Task<Policy>> getPolicyTasks = from policy in policyList select GetPolicyDetailAsync(policy);

IEnumerable<Task<Policy>> tasks = policyList.Select(policy => Task.Run(() => GetPolicyDetailAsync(policy)));

var policyResults = await Task<Policy>.WhenAll(tasks);

but this doesn't?

List<Task<Policy>> getPolicyTasks = new List<Task<Policy>>();

foreach (var policy in policyList)
      getPolicyTasks.Add(GetPolicyDetailAsync(policy));

var policyResults = await Task.WhenAll(getPolicyTasks);

policies = policyResults.ToList();

The GetPolicyAsync is a straightforward Dapper SQL call like such:

policies = await db.QueryAsync<Policy, Address, Policy>(sql,
   (policy, address) =>
   {
       policy.Address = address;
       return policy;
   },
   param: new { input = policy },
   splitOn: "Address1");

return policy;

It seems all of my services that the API call need to use Task.Run() to run async. Why is this the case when the methods are async and awaited?

1 Answers

It turns out IBM DB2 provider doesn't fully support async operations and thus why I need to use Task.Run for it. Makes sense. Thanks @Charlieface for pointing me in the right direction.

Related