0

I'm learning the usage of async and await, and tried to do the following:

I have an array of numbers in a particular order, and an async method that gets a number and a time delay, and return the same passed-in number.

What I'd like to achieve is to print the numbers in a reveresed order (relative to the calling order), utilizing the time delay.

I'm having a hard time figuring out how to do it, and be glad for a guidance. Here's what I have (which, ofcourse, doesn't work):

public static async Task<int> DelayAndReturn(int number, int milisecDelay)
{
    await Task.Delay(milisecDelay);
    return number;
}

public static void Main(string[] args)
{
    int[] arr = { 1, 2, 3 };
    int milisecDelay = 10000;
    foreach (int num in arr)
    {
       Console.WriteLine(DelayAndReturn(num, milisecDelay));
       milisecDelay /= 10;
    }
    Console.ReadLine();
}
OfirD
  • 9,442
  • 5
  • 47
  • 90

1 Answers1

0

DelayAndReturn returns a Task object and the correct way to get the result of that object is to await the task. However, awaiting the task will also stop your foreach until 10000 ms have passed, and only then send the next item for processing.

Note that, although the code execution is waiting for the asynchronous operation to complete, the thread is free to be used by other processes.

Your best bet to get them printed in reversed order, is to create a collection of tasks and await all of them.

public static async Task DelayAndReturn(int number, int milisecDelay)
{
    await Task.Delay(milisecDelay);
    Console.WriteLine(number);
}

public static void Main(string[] args)
{
    PrintReversed().GetAwaiter().GetResult();
}

public static async Task PrintReversed() {
    int[] arr = { 1, 2, 3 };
    int milisecDelay = 1000;

    List<Task> tasks = new List<Task>();
    foreach (int num in arr)
    {
       tasks.Add(DelayAndReturn(num, milisecDelay));
       milisecDelay /= 10;
    }

    await Task.WhenAll(tasks);
}
edo.n
  • 2,184
  • 12
  • 12