0

Why does method Redraw executes before all tasks ended?

I have break point in both lines: Redraw and _images.Add(image); and breakpoint hits Redraw before _images.Add(image);

var tasks = new List<Task>();

foreach (var url in result)
{
    tasks.Add(Task.Factory.StartNew(async () =>
    {
        var image = await http.DownloadImagesAsync(url);
        _images.Add(image);
    }));
}

await Task.WhenAll(tasks);

Redraw();
Axelly
  • 589
  • 3
  • 7
  • 26
  • 1
    `Task.Run`, not `Task.Factory.StartNew` (`Task.Run` has an overload which takes a `Func`; `Task.Factory.StartNew` doesn't, which means your `async ()` lambda is being turned into an `async void` method) – canton7 Jun 19 '20 at 15:00
  • Because you create a fire and forget lambda to run in a new thread. – juharr Jun 19 '20 at 15:00
  • You're creating tasks that wrap tasks. The outer task just creates the inner task; that action is quick and finishes almost immediately. You're checking the outer tasks – Damien_The_Unbeliever Jun 19 '20 at 15:00
  • 1
    Also you should not add to ordinary list from multiple threads. – Guru Stron Jun 19 '20 at 15:02
  • 1
    You are wasting threads by using them to run async I/O operations. Add the Task from `http.DownloadImagesAsync` directly to `tasks`. – Crowcoder Jun 19 '20 at 15:02
  • @GuruStron They're not. That code is adding tasks to the list synchronously. – itsme86 Jun 19 '20 at 15:03
  • 4
    You likely want `_images.AddRange(await Task.WhenAll(result.Select(url => http.DownloadImagesAsync(url))));` – juharr Jun 19 '20 at 15:05
  • 2
    @itsme86 He's talking about the `_images` list – juharr Jun 19 '20 at 15:06
  • @itsme86 yes, got confused with `_images.Add(image)` =) – Guru Stron Jun 19 '20 at 15:08
  • @canton7 in this case the async lambda is not actually converted to async void, because the `Task.Factory.StartNew` has an overload `StartNew(Func)`, and the `TResult` is resolved as `Task`. Hence it returns a `Task`. Async voids are created when async lambdas are passed to `Action` parameters. – Theodor Zoulias Jun 19 '20 at 17:36

0 Answers0