Richard Sustek Richard Sustek - 2 months ago 14
C# Question

Performance impact of using async await when its not necessary

Let's assume I have these methods:

public async Task<Something> GetSomethingAsync()
{
var somethingService = new SomethingService();

return await service.GetAsync();
}


and

public Task<Something> GetSomethingAsync()
{
var somethingService = new SomethingService();

return service.GetAsync();
}


Both options compile and work the same way. Is there any best practise as to which option is better of if one is faster then the other?

Or is it just some syntactic sugar?

Answer

In the first method compiler will generate "state machine" code around it and execution will be returned to the line return await service.GetAsync(); after task will be completed. Consider example below:

public async Task<Something> GetSomethingAsync()
{
    var somethingService = new SomethingService();

    // Here execution returns to the caller and returned back only when Task is completed.
    Something value = await service.GetAsync(); 

    DoSomething();

    return value;        
}

The line DoSomething(); will be executed only after service.GetAsync task is completed.

Second approach simply starts execution of service.GetAsync and return correspondent Task to the caller without waiting for completion.

public Task<Something> GetSomethingAsync()
{
    var somethingService = new SomethingService();

    Task<Something> valueTask = service.GetAsync(); 

    DoSomething();

    return valueTask;        
}

So in the example above DoSomething() will be executed straight after line Task<Something> valueTask = service.GetAsync(); without waiting for completion of task.

Executing async method on the another thread depend on the method itself.

If method execute IO operation, then another thread will be only waste of the thread, which do nothing, only waiting for response. On my opinion async - await are perfect approach for IO operations.

If method GetAsync contains for example Task.Run then execution goes to the another thread fetched from thread pool.

Comments