Is this the correct use of await / async?

I am new to async / await and I want to make sure this way to do it right:

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 right, or have I done something wrong?

+4
source share
2 answers

There are a few things you can do:

  • In DoHeavyWorkAsyncyou do not need to create a state machine with await Task.Run, you can simply return Task.Run:

    public Task DoHeavyWorkAsync() 
    {
       return Task.Run(() => getResponseFromFarawaySlowServerAndDoSomethingWithIt());
    }
    
  • async voidapplies exclusively to async event handlers . If your async method returns void, it should return Taskinstead:

    public async Task ConsumeAsync()
    
  • DoHeavyWorkAsync - -, Task.Run, . await. , . Task.Run, :

    public void DoHeavyWork()
    {
        getResponseFromFarawaySlowServerAndDoSomethingWithIt();  
    }
    

    :

    Task.Run(DoHeavyWork);
    
+7

API, getResponseFromFarawaySlowServerAndDoSomethingWithIt:
 getResponseFromFarawaySlowServer doSomething().
async

:

var response = await getResponseFromFarawaySlowServerAsync();
doSomething(response);

, : getResponseFromFarawaySlowServer . http webservice , . , . , http-

string getResponseFromFarawaySlowServer(){
  string response = new WebClient().DownloadString(uri);
  ...
  return response
}

async Task<string> getResponseFromFarawaySlowServerAsync(){ Task.StartNew..

:

async Task<string> getResponseFromFarawaySlowServerAsync(){
  string response = await new WebClient().DownloadStringAsync(uri);
  ...
  return response;
}
+2

All Articles