Async methods can have the following return types:
- Task, for an async method that performs an operation but returns no value.
- Task
, for an async method that returns a value. void
, for an event handler.- Any type that has an accessible
GetAwaiter
method. The object returned by theGetAwaiter
method must implement the System.Runtime.CompilerServices.ICriticalNotifyCompletion interface. - IAsyncEnumerable
, for an async method that returns an async stream.
Use Task instead of void because an async method that returns void cannot be awaited.
ValueTask: Benefits over ref inherent in task is performance for a tight loop, etc.
Because Task and Task
.NET provides the System.Threading.Tasks.ValueTask
Async streams with IAsyncEnumerable
An async method might return an async stream, represented by IAsyncEnumerable
C#Copy
static async IAsyncEnumerable<string> ReadWordsFromStreamAsync()
{
string data =
@"This is a line of text.
Here is the second line of text.
And there is one more for good measure.
Wait, that was the penultimate line.";
using var readStream = new StringReader(data);
string? line = await readStream.ReadLineAsync();
while (line != null)
{
foreach (string word in line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
yield return word;
}
line = await readStream.ReadLineAsync();
}
}
The preceding example reads lines from a string asynchronously. Once each line is read, the code enumerates each word in the string. Callers would enumerate each word using the await foreach
statement. The method awaits when it needs to asynchronously read the next line from the source string.