0

so I have an async method wrapped in Task.Run like so:

//SynchronisationContext = UI Thread
await Task.Run(async => 
{
    for (int i = 0; i < 100; i++)
    {
       var res = ComplicatedCalulation(); //Takes about 1 second
       await ThirdPartyLib.WriteToDatabase(res);
    }
});

Does the await on the above code await the async lambda code or does it just await the Task being started (i.e. returning straight away)

I know with Task.Factory.StartNew the correct use is

await Task.Factory.StartNew<Task>(async => await MyAsyncMethod()).Result

Is this also true for Task.Run?

JKennedy
  • 18,150
  • 17
  • 114
  • 198
  • Maybe this (and its associated links) by *Stephen Cleary* , https://stackoverflow.com/questions/32591462/is-using-an-an-async-lambda-with-task-run-redundant – TheGeneral Jul 09 '19 at 08:59
  • 2
    `Task.Result` is so seldom the right choice that I find myself questioning whether it really is the "correct use" here... – spender Jul 09 '19 at 09:05
  • @TheGeneral I'm not sure its correct. His advise is to avoid that situation, but I think I have a valid use. I have added some context to the `Task` method – JKennedy Jul 09 '19 at 09:15
  • 3
    The `StartNew` example should use `Unwrap`, not `Result`. Also, I strongly recommend always passing a `TaskScheduler` to `StartNew`. Or, better yet, just use `Task.Run`, which does both of these for you. – Stephen Cleary Jul 09 '19 at 19:57

1 Answers1

0

Your code will wait till the end of the compute using the task mechanism. This will not block your thread but it will not execute code beyond this point until everything in your loop is done.

public static async Task Test()
{
    await Task.Run(async () => 
    {
        for (int i = 0; i < 10; i++)
        {
            await Task.Delay(TimeSpan.FromSeconds(1));
            Console.WriteLine($"inside {i}");
        }
    });
    Console.WriteLine("Done");
}

will give the following output:

inside 0
inside 1
inside 2
inside 3
inside 4
inside 5
inside 6
inside 7
inside 8
inside 9
Done
Bruno Belmondo
  • 2,299
  • 8
  • 18