Guide to the Language


Download 2 Mb.
Pdf ko'rish
bet77/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   70   71   72   73   74   75   76   77   78
Bog'liq
C sharp

 Async Streams
Async streams were added in C# 8.0, allowing async methods to return 
multiple results. This broadens their usability, enabling async methods to 
return data as it becomes available. The async stream (producer method) 
uses a yield return statement. This returns the result to the caller and 
then continues to execute the method, allowing the method to make 
asynchronous calls in between yielding each result.
Chapter 30 asynChronous Methods


182
using System.Collections.Generic;
using System.Threading.Tasks;
static async IAsyncEnumerable MyStream(int count)
{
int sum = 0;
for (int i = 0; i <= count; i++)
{
sum = sum + i;
yield return sum; // return a result
// Simulate waiting for more data
await Task.Delay(1000);
}
// end stream
}
For the purpose of async streams, C# 8.0 added asynchronous versions 
of the generic enumerator interfaces. The IAsyncEnumerable interface 
is used here for returning a stream that can be consumed using an await 
foreach loop. This variant of the foreach loop was also introduced with C# 8.0.
static async Task Main()
{
await foreach (int data in MyStream(3))
{
System.Console.Write(data + " "); // "0 1 3 6"
}
}
Chapter 30 asynChronous Methods


183
© Mikael Olsson 2020 
M. Olsson, C# 
8
 Quick Syntax Reference
https://doi.org/10.1007/978-1-4842-5577-3
Index
A
Abstract methods
classes and interfaces, 
111,
112
GetArea class, 
110
members, 
109
Access levels, 
77
guideline, 
83
inner classes, 
82
internal member, 
79
private access, 
77,
78
private protected member
80
protected/internal, 
80
protected member, 
78
public modifier, 
81
top-level member, 
82
Anonymous methods, 
63,
146
Arithmetic operators
15
Array
access, 
26
allocation, 
25
assignment, 
26
declaration, 
25
jagged arrays, 
27
rectangular, 
26
Assignment operators, 
16
combined operators, 
16
increment (++) and
decrement (--), 
16
Asynchronous methods
async and await keyword
177
extended return types, 
180
methods, 
179
return types, 
178
streams, 
181,
182

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   70   71   72   73   74   75   76   77   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling