111

I'm trying to create an asynchronous console app that does a some work on a collection. I have one version which uses parallel for loop another version that uses async/await. I expected the async/await version to work similar to parallel version but it executes synchronously. What am I doing wrong?

public class Program 
{
    public static void Main(string[] args) 
    {
        var worker = new Worker();
        worker.ParallelInit();
        var t = worker.Init();
        t.Wait();
        Console.ReadKey();
    }
}

public class Worker 
{
    public async Task<bool> Init() 
    {
        var series = Enumerable.Range(1, 5).ToList();
        foreach(var i in series) 
        {
          Console.WriteLine("Starting Process {0}", i);
          var result = await DoWorkAsync(i);
          
          if (result) 
          {
            Console.WriteLine("Ending Process {0}", i);
          }
        }

        return true;
    }

    public async Task<bool> DoWorkAsync(int i) 
    {
        Console.WriteLine("working..{0}", i);
        await Task.Delay(1000);
        
        return true;
    }

    public bool ParallelInit() 
    {
        var series = Enumerable.Range(1, 5).ToList();
        
        Parallel.ForEach(series, i => 
        {
            Console.WriteLine("Starting Process {0}", i);
            DoWorkAsync(i);
            Console.WriteLine("Ending Process {0}", i);
        });
        
        return true;
    }

}

6 Answers 6

150

The way you're using the await keyword tells C# that you want to wait each time you pass through the loop, which isn't parallel. You can rewrite your method like this to do what you want, by storing a list of Tasks and then awaiting them all with Task.WhenAll.

public async Task<bool> Init()
{
    var series = Enumerable.Range(1, 5).ToList();
    var tasks = new List<Task<Tuple<int, bool>>>();
    foreach (var i in series)
    {
        Console.WriteLine("Starting Process {0}", i);
        tasks.Add(DoWorkAsync(i));
    }
    foreach (var task in await Task.WhenAll(tasks))
    {
        if (task.Item2)
        {
            Console.WriteLine("Ending Process {0}", task.Item1);
        }
    }
    return true;
}

public async Task<Tuple<int, bool>> DoWorkAsync(int i)
{
    Console.WriteLine("working..{0}", i);
    await Task.Delay(1000);
    return Tuple.Create(i, true);
}
8
  • 4
    I don't know about others, but a parallel for/foreach seems more straight forward for parallel loops.
    – Brettski
    Feb 13, 2014 at 19:07
  • 13
    Important to note that when you see the Ending Process notification isn't when the task is actually ending. All of those notifications are dumped out sequentially right after the last of the tasks finishes. By the time you see "Ending Process 1", process 1 might have been over for a long time. Other than the choice of words there, +1. Apr 17, 2014 at 0:31
  • @Brettski I may be wrong, but a parallel loop traps any sort of async result. By returning a Task<T> you immediately get back a Task object in which you can manage the work that is going on inside such as cancelling it or seeing exceptions. Now with Async/Await you can work with the Task object in a more friendly manner - that is you don't have to do Task.Result. Jan 21, 2015 at 17:53
  • @Tim S, what if I want to return a value with async function using Tasks.WhenAll method?
    – Mihir
    Apr 10, 2018 at 13:59
  • Would it be a bad practice to implement a Semaphore in DoWorkAsync to limit the maximum executing tasks?
    – C4d
    May 31, 2018 at 6:31
41

Your code waits for each operation (using await) to finish before starting the next iteration.
Therefore, you don't get any parallelism.

If you want to run an existing asynchronous operation in parallel, you don't need await; you just need to get a collection of Tasks and call Task.WhenAll() to return a task that waits for all of them:

return Task.WhenAll(list.Select(DoWorkAsync));
6
  • so you cant use any asynchronous methods in any loops?
    – Satish
    Oct 17, 2013 at 15:57
  • 4
    @Satish: You can. However, await does the exact opposite of what you want – it waits for the Task to finish.
    – SLaks
    Oct 17, 2013 at 15:58
  • I wanted to accept your answer but Tims S has a better answer.
    – Satish
    Oct 17, 2013 at 16:09
  • Or if you don't need to know when the task finished you can just call the methods without awaiting for them
    – disklosr
    Mar 25, 2016 at 7:27
  • To confirm what that syntax is doing - it's running the Task called DoWorkAsync on each item in list (passing each item into DoWorkAsync, which I assume has a single parameter)?
    – jbyrd
    Jan 4, 2018 at 18:37
14
public async Task<bool> Init()
{
    var series = Enumerable.Range(1, 5);
    Task.WhenAll(series.Select(i => DoWorkAsync(i)));
    return true;
}
9

In C# 7.0 you can use semantic names to each of the members of the tuple, here is Tim S.'s answer using the new syntax:

public async Task<bool> Init()
{
    var series = Enumerable.Range(1, 5).ToList();
    var tasks = new List<Task<(int Index, bool IsDone)>>();

    foreach (var i in series)
    {
        Console.WriteLine("Starting Process {0}", i);
        tasks.Add(DoWorkAsync(i));
    }

    foreach (var task in await Task.WhenAll(tasks))
    {
        if (task.IsDone)
        {
            Console.WriteLine("Ending Process {0}", task.Index);
        }
    }

    return true;
}

public async Task<(int Index, bool IsDone)> DoWorkAsync(int i)
{
    Console.WriteLine("working..{0}", i);
    await Task.Delay(1000);
    return (i, true);
}

You could also get rid of task. inside foreach:

// ...
foreach (var (IsDone, Index) in await Task.WhenAll(tasks))
{
    if (IsDone)
    {
        Console.WriteLine("Ending Process {0}", Index);
    }
}
// ...
2
  • Say the for loop enumerates over 10000 records. Say the present iteration is 6000 and at this point one of the initial task (Say task 1) has finished awaiting the Task.Delay. Now, at this point, will the code below await in Task 1 run immediately or will it wait for entire for loop to complete? Would this behavior differ whether it is a console app or a windows forms app?
    – variable
    Aug 1, 2021 at 13:43
  • I get Warning CS4014 Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. when in a async method, foreach loop call sync method
    – Kiquenet
    Dec 8, 2022 at 11:40
1

We can use async method in foreach loop to run async API calls.

public static void Main(string[] args)
{

List<ZoneDetails> lst = GetRecords();

    foreach (var item in lst)
    {
        //For loop run asyn
        var result = GetAPIData(item.ZoneId, item.fitnessclassid).Result;
        if (result != null && result.EventHistoryId != null)
        {
            UpdateDB(result);
        }
    }
}

private static async Task<FODBrandChannelLicense> GetAPIData(int zoneId, int fitnessclassid)
{

    HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var response = HttpClient.GetAsync(new Uri(url)).Result;

    var content = response.Content.ReadAsStringAsync().Result;
    var result = JsonConvert.DeserializeObject<Model>(content);

    if (response.EnsureSuccessStatusCode().IsSuccessStatusCode)
    {
        Console.WriteLine($"API Call completed successfully");

    }

    return result;
}
1
  • 1
    Try async in Main method ?
    – Kiquenet
    Dec 8, 2022 at 11:42
0

To add to the already good answers here, it's always helpful to me to remember that the async method returns a Task.

So in the example in this question, each iteration of the loop has await. This causes the Init() method to return control to its caller with a Task<bool> - not a bool.

Thinking of await as just a magic word that causes execution state to be saved, then skipped to the next available line until ready, encourages confusion: "why doesn't the for loop just skip the line with await and go to the next statement?"

If instead you think of await as something more like a yield statement, that brings a Task with it when it returns control to the caller, in my opinion flow starts to make more sense: "the for loop stops at await, and returns control and the Task to the caller. The for loop won't continue until that is done."

1

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.