[Solved] C#: Why does it take so long to get a Task t.Result when the task has already finished? [closed]


I’ll update this as you update your question, but here’s my best guess.

This line doesn’t compile, because Select doesn’t return a List:

List<Task<T>> myTasks = someList.Select(x => Task.Run(() => DoSomethingWith(x)));

I’m going to hazard a guess that you’re actually doing this:

var myTasks = someList.Select(x => Task.Run(() => DoSomethingWith(x)));

… which produces a cold IEnumerable: one which will only run when it actually gets iterated over.

In the code above, you’re iterating over it when you call .ToArray() on it. But the line you describe as taking 25ms is likewise producing nothing but another cold IEnumerable<>. No real work is being done here:

var myResults = myTasks.Select(task => task.Result);

So again I’m going to hazard a guess that you’re doing something more like this:

var myResults = myTasks.Select(task => task.Result).ToList();

… which is going to iterate over myTasks a second time, causing Task.Run(...) to get called again for each item in someList, and then waiting for all of those tasks to complete.

In other words, you’re doing the work twice, and one of those times in in the line that you reference at the end.

Fortunately, there is a better way to do what you’re doing, using the Task Parallel Library.

var myResults = someList
    .AsParallel()
    .Select(x => DoSomethingWith(x))
    .ToList();

4

solved C#: Why does it take so long to get a Task t.Result when the task has already finished? [closed]