Skip to content

Latest commit

 

History

History
29 lines (23 loc) · 962 Bytes

PH_P011.md

File metadata and controls

29 lines (23 loc) · 962 Bytes

PH_P011 - Replace With Async Stream

Problem

A collection is asynchronously populated and returned inside a task in the form Task<IEnumerable<...>>. However, such implementations require that the consumer awaits the complete result instead of single items. The example below illustrates such a constellation.

public Task<IEnumerable<string>> GetRandomTextsAsync(int total) {
	var result = new List<int>();
	for(int i = 0; i < total; i++) {
		var text = await /* ... */;
		result.Add(text);
	}
	return text;
}

Solution

C# 8 and .NET Core 3.0 introduced async streams. Async streams allow the consumer to await the items instead of the complete response to process them individually. The example below illustrates the refactored implementation from the problem statement.

public IAsyncEnumerable<string> GetRandomTextsAsync(int total) {
	for(int i = 0; i < total; i++) {
		var text = await /* ... */;
		yield return text;
	}
}