1

I am currently investigating for a project if there is a signification performance difference the following Methods:

    [HttpGet]
    public async Task<IHttpActionResult> Test1()
    {
        await Task.Delay(TimeSpan.FromSeconds(10));
        return Ok();
    }

and

    [HttpGet]
    public IHttpActionResult Test2()
    {
        Thread.Sleep(TimeSpan.FromSeconds(10));
        return Ok();
    }

In my understanding the first method Test1 is executed asynchronous, which means the result of the task.delay is awaited and the current thread can be reused by an other request.

The second method Test2 is executed synchronous and the thread is blocked for 10 seconds. Nevertheless the OK result is executed asynchronous since my return type is IHttpActionResult.

My questions are the following:

  1. Is there a benefit of returning a IHttpActionResult vs a Task< IHttpActionResult >?
  2. I tested both methods on my local machine using wcat Performance tool using 2 clients with 40 virtual clients and both methods resulted in the similar results. I expected that with the first method I would be able to execute more requests than with the second one. So either my setup of this test is wrong or I misunderstood the effects of async / synchronous execution?

Looking forward to your answers!

Bryan Pendleton
  • 16,128
  • 3
  • 32
  • 56
wami
  • 435
  • 3
  • 10
  • the first method awaits in a different thread. the second one blocks the current thread. Anyway, a better usage would be await Task.Delay(10) instead of Thread.Sleep(10) the second one you waste resourced by having a thread blocked doing nothing, the first one releases the calling thread and will resume work at some other point, is like promises in Javascript, when you await, you make a promise that eventually you will return something or an exception – rmjoia Sep 28 '17 at 10:16
  • I find this book very good as it's very small and nuclear [Async in C# 5.0](http://shop.oreilly.com/product/0636920026532.do) – rmjoia Sep 28 '17 at 10:20

1 Answers1

0

You would only see the benefit of running the Async method if you can put your site under load - i.e. run a decent number of requests at the same time. Simply running each once you will see no difference.

Async code doesn't run any faster; it allows the system to manage its threadpool and improve concurrency - i.e. the available threads can be used more efficiently.

See Stephen Cleary's explanation:

Async and Await

Phil S
  • 642
  • 8
  • 19