Consider the following method:
public async Task<string> GetNameOrDefaultAsync(string name)
{
if (name.IsNullOrDefault())
{
return await GetDefaultAsync();
}
return name;
}
When name
is provided, no awaiting will occur in the method execution, yet this method will compile correctly.
However, this method will produce the build warning shown below:
public async Task<string> GetDefaultAsync()
{
return "foobar";
}
[CS1998] This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
Why is it that GetNameOrDefaultAsync
can return without ever awaiting, and not result in a compiler warning, but GetDefaultAsync
must await in order to compile?
Would it be an improvement to do the following?:
public async Task<string> GetNameOrDefaultAsync(string name)
{
if (name.IsNullOrDefault())
{
return await GetDefaultAsync();
}
return await Task.FromResult(name);
}
Here we would have no execution paths that don't await
something.