Should I add async / wait for a single line function or not?

Should I add async / wait to a single line function, for example:

public async Task<T> GetFoo()
{
    return await HandleAsync<T>(....);
}

Or is it unnecessary overhead if the parameter does not need an asynchronous call, and I can simply write:

public Task<T> GetFoo()
{
    return HandleAsync<T>(....);
}
+4
source share
3 answers

Use the second overload because asynchronous conversion methods are converted to an asthmatic machine behind the scenes (an extra class) to handle asynchronous work with waiting.

So, the first method adds extra overhead. The second overload just returns the task you can still expect.

I'm not sure that exception handling has changed here, but I think this will not change.

+4
source

, . task, , , . , , . .

:

public Task DownloadStream(Stream target)
{
 return _downloader.ToStream(target);
}

, , , , ..:

public async Task DownloadAsync()
{
  Using(var stream = new MemoryStream(){
    await DownloadStream(stream); //<== here i NEED to wait and not block the UI
  }
}

, .

!

0

async/await , . - , - , , Task<T> - .

, , , , . . , , , , , #.

0
source

Source: https://habr.com/ru/post/1687615/


All Articles