Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check possibility of deadlock in c# code

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 ?

like image 738
Pரதீப் Avatar asked Mar 04 '23 19:03

Pரதீப்


1 Answers

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);
}
like image 180
Fabio Avatar answered Mar 09 '23 06:03

Fabio