-1

For example, we have two snippets of code:

  1. public static async Task TestAsync()  
    {
        await Task.Delay(5000);
    }        
    
    Task.Run(async () => 
    {
        for (int i = 0; i < 3; ++i)
        {
            await TestAsync();
        }
    }).Wait();
    
  2. public static void Test()
    {
        Task.Delay(5000).Wait();
    }
    
    Task.Run(() => 
    {
        for (int i = 0; i < 3; ++i)
        {
            Test();
        }
    }).Wait();
    

(Task.Delay just represents some long running job.)

Will there be any performance difference between the two snippets of code? (I tested them, and it seems they have same performance.)

But, in theory, will 2) outperform 1) in some situation? (For example, if there are a lot of threads waiting to be executed in the thread pool.)

GSerg
  • 76,472
  • 17
  • 159
  • 346
Shane Lu
  • 1,056
  • 1
  • 12
  • 21
  • Both [call `Wait` on the outer result](https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html). Both run a separate thread to run the code. – GSerg May 20 '19 at 15:25
  • An await is not for free. But right now the delay is so long that you can't see the extra overhead imposed by the thread context switches. That's normal and expected in async code, you made it async because it is slow. So nothing to worry about. – Hans Passant May 20 '19 at 15:32
  • [Race your horses](https://ericlippert.com/2012/12/17/performance-rant/) – Dmytro Mukalov May 20 '19 at 18:26
  • @GSerg The wait of the outer result was in a main function of a console application. I have to wait somewhere or the main thread will just exit. Is my understanding correct? Besides, I just want to know if there will be any performance penalty in either of the two options. For example, is it possible for the first option to be run on 2 separate threads (since there are awaits) in order? – Shane Lu May 21 '19 at 03:22
  • @ShaneLu Yes, you have to wait in a console application if your `Main` is not async. Regarding threads, both use one, and run one `Test()` at a time. – GSerg May 21 '19 at 07:05

1 Answers1

0

Number 2) will actually block a thread as you are using Wait. So best practice would be to use approach 1), regardless of your performance. Wait will synchronously block that thread until the associated task is completed.

I know this may not be the answer you wanted but you could also checkout:

await vs Task.Wait - Deadlock?

MSDN Article Async/Await Best Practices

JEV
  • 2,494
  • 4
  • 33
  • 47