How to check possibility of deadlock in c# code

2019-04-09 15:00发布

My application sometimes stop in the below code, not always but sometimes.

All the 3 methods CalcQuarterlyFigures, CalcWeeklyFigures & CalcMonthlyFigures return Task<List<MyClass>>.

Note, this runs inside a foreach loop.

List<Task> TaskList = new List<Task>();

if(i.DoCalculateAllHistory) {

    var quarterly = CalcQuarterlyFigures(QuarterlyPrices, i.SeriesID);
    TaskList.Add(quarterly);
    var weekly = CalcWeeklyFigures(WeeklyPrices, i.SeriesID);
    TaskList.Add(weekly);
    var monthly = CalcMonthlyFigures(MonthlyPrice, i.SeriesID);
    TaskList.Add(monthly);

    Task.WaitAll(TaskList.ToArray());

    if(monthly.Result.Count > 0)
        monthlyPerfFig.AddRange(monthly.Result);

    if(weekly.Result.Count > 0)
        weeklyPerfFig.AddRange(weekly.Result);

    if(quarterly.Result.Count > 0)
        quartPerfFig.AddRange(quarterly.Result);
} else {

    monthlyPerfFig.AddRange(await CalcMonthlyFigures(MonthlyPrice, i.SeriesID));

}

Am I missing anything here that leads to dead lock ?

1条回答
做个烂人
2楼-- · 2019-04-09 15:16

In provided context (sample code of .NET 4.6.1) Task.WaitAll(TaskList.ToArray()) will cause a deadlock.
Definitely useful source: Don't Block on Async Code

You should make you code block fully asynchronous

if (i.DoCalculateAllHistory) 
{
    var quarterlyTask = CalcQuarterlyFigures(QuarterlyPrices, i.SeriesID);
    var weeklyTask = CalcWeeklyFigures(WeeklyPrices, i.SeriesID);
    var monthlyTask = CalcMonthlyFigures(MonthlyPrice, i.SeriesID);

    // Task.WhenAll accepts "params" array
    await Task.WhenAll(quarterlyTask, weeklyTask, monthlyTask);

    // You don't need to check for .Count
    // nothing will be added when empty list given to .AddRange  
    quartPerfFig.AddRange(await quarterlyTask);
    weeklyPerfFig.AddRange(await weeklyTask);
    monthlyPerfFig.AddRange(await monthlyTask);
} 
else 
{
    var monthly = await CalcMonthlyFigures(MonthlyPrice, i.SeriesID);
    monthlyPerfFig.AddRange(monthly);
}
查看更多
登录 后发表回答