My MVC app ocasionally results in a deadlock. I think it is likely due to a faulty way I am collecting data from completed async tasks.
I have two independent async methods.
var task1 = GetNamesFromSource1Async(); // a database call, may throw an exception
var task2 = GetNamesFromSource2Async(); // a database call, may throw an exception
var total = new List<string>();
await Task.WhenAll(task1, taks2).ConfigureAwait(false);
Question part 1: What is the safest recommended way and the best practice to collect results from these tasks:
// here I already know that both tasks are completed and
// I am using (or abusing?) await to get task results
List<string> names1 = await task1.ConfigureAwait(false);
List<string> names2 = await task2.ConfigureAwait(false);
if (names1 != null) total.AddRange(names1);
if (names2 != null) total.AddRange(names2);
or
total.AddRange(task1.IsFaulted ? new List<string> : task1.Result);
total.AddRange(task2.IsFaulted ? new List<string> : task2.Result);
?
Question part 2: in addition if I want to transform data from the first source, is it safe to use ContinueWith (when I say safe I mean from the standpoint of deadlocks)
var task1 = GetNamesFromSource1Async().ContinueWith(t =>
{
if ( !t.IsFaulted && t.Result != null)
{
return t.Result.Take(1).ToList();
}
});
Remark: here I am trying control for exceptions within each of the tasks by checking IsFaulted flag.
A recommendation on the best practice to solve this problem would be highly appreciated. I am using .NET 4.5
> but task2 is Task
– AstroSharp Feb 24 '17 at 17:33> ?