C#C
C#4y ago
Gladiator

❔ Task.WhenAll does not work without Task.Run inside

Inside a task, _pathFinder.FindPath is not called.
returnFirstPath is false (Task.WhenAll)
but if I change list.Add(new Task<PathResult>(action)); to list.Add(Task.Run(action));, it works.
Another question, I should use Task.Run to be sure it runs in different threads and get results faster?
    for (var j = 0; j < roadPoints.Length; j++)
                {
                    var j1 = j;
                    Func<PathResult> action = () =>
                    {
                        var pathResult = _pathFinder.FindPath
                        (
                            sourcePoint,
                            setting.SearchRange,
                            roadPoints[j1],
                            CheckTarget,
                            CheckObstacle,
                            ComputeWeight
                        );
                        return pathResult;
                    };
                    list.Add(new Task<PathResult>(action));
                }

                PathResult pathResult;
                if (returnFirstPath)
                {
                    pathResult = await await Task.WhenAny(list);
                }
                else
                {
                    var pathResults = await Task.WhenAll(list);
                    pathResult = pathResults.MinBy(p => p.Path.Length);
                }
Was this page helpful?