Chin Chin - 2 months ago 10
C# Question

Is this usage of await/async correct?

I'm new to async/await and I want to make sure that this way of doing it is correct:

public async Task DoHeavyWorkAsync()
{
await Task.Run(() => {
getResponseFromFarawaySlowServerAndDoSomethingWithIt();
});
}

public async void ConsumeAsync()
{
Task longRunningTask = DoHeavyWorkAsync();
// do a lot of other stuffs here that does not depend on DoHeavyWorkAsync()
await longRunningTask;
}


Is this way of using async/await correct or did I do something wrong?

Answer

There are a couple of things you can do:

  1. In DoHeavyWorkAsync, you don't really need to generate a state machine using await Task.Run, you can simply return Task.Run:

    public Task DoHeavyWorkAsync() 
    {
       return Task.Run(() => getResponseFromFarawaySlowServerAndDoSomethingWithIt());
    }
    
  2. async void is ment solely for async Event Handlers. If your async method is void returning, it should return a Task instead:

    public async Task ConsumeAsync()
    
  3. If DoHeavyWorkAsync is an IO based operation, there is no need to wrap it inside a Task.Run as it is inherently asynchronous. Simply using await will do. More-so, you shouldn't do async over sync. Instead, you should make the caller of the synchronous method explicitly use Task.Run, if needed at all:

    public void DoHeavyWork()
    {
        getResponseFromFarawaySlowServerAndDoSomethingWithIt();  
    }
    

    and then explicitly wrap it in the calling method:

    Task.Run(DoHeavyWork);
    
Comments