如何检查c#代码中死锁的可能性

How to check possibility of deadlock in c# code

我的应用程序有时会在下面的代码中停止,并非总是如此,但有时会。

所有 3 种方法 CalcQuarterlyFiguresCalcWeeklyFigures & CalcMonthlyFigures return Task<List<MyClass>>

注意,这在 foreach 循环中运行。

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));

}

我是否遗漏了导致死锁的任何内容?

在提供的上下文中(.NET 4.6.1 的示例代码)Task.WaitAll(TaskList.ToArray()) 将导致死锁。
绝对有用的来源:Don't Block on Async Code

你应该让你的代码块完全异步

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);
}