Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# TaskWhenAll on method which is returing result depending on awaited call

i'm trying to make this code works in async way, but i got some doubts.

public async Task<string> GetAsync(string inputA, string inputB)
{
    var result = await AnotherGetAsync(inputA, inputB)
        .ConfigureAwait(false);

    return result.Enabled
        ? inputB
        : string.Empty;
}

I got some string input collection, and i would like to run this method on them. Then i would do Task.WhenAll, and filter for non empty strings.

But it won't be async as inside the method i'm already awaiting for the result right?

like image 351
paski Avatar asked Dec 11 '19 10:12

paski


1 Answers

I assumed the real question is:

If a single item is awaited inside method A, will this run sequential if I use Task.WhenAll for a range of items calling method A?

They will be run simultaneous with Task.WhenAll. Perhaps it is best explained with an example:

void Main()
{
    Test().GetAwaiter().GetResult();
}

private async Task<bool> CheckEmpty(string input)
{
    await Task.Delay(200);
    return String.IsNullOrEmpty(input);
}

private async Task Test()
{
    var list = new List<string>
    {
        "1",
        null,
        "2",
        ""
    };

    var stopwatch = new Stopwatch();
    stopwatch.Start();

    // This takes aprox 4 * 200ms == 800ms to complete.
    foreach (var itm in list)
    {
        Console.WriteLine(await CheckEmpty(itm));
    }

    Console.WriteLine(stopwatch.Elapsed);
    Console.WriteLine();
    stopwatch.Reset();
    stopwatch.Start();

    // This takes aprox 200ms to complete.
    var tasks = list.Select(itm => CheckEmpty(itm));
    var results = await Task.WhenAll(tasks); // Runs all at once.
    Console.WriteLine(String.Join(Environment.NewLine, results));
    Console.WriteLine(stopwatch.Elapsed);
}

My test results:

False
True
False
True
00:00:00.8006182

False
True
False
True
00:00:00.2017568
like image 155
Silvermind Avatar answered Sep 22 '22 07:09

Silvermind