C# 8.0 中的异步流是什么?

来源:这里教程网 时间:2026-02-21 16:20:20 作者:

c# 8.0 中的异步流是什么?

C# 8.0 introduces async streams, which model a streaming source of data. Data 流通常异步地检索或生成元素。

生成序列的代码现在可以使用yield return以返回元素

使用async修饰符声明的方法。

我们可以使用await foreach循环消费异步流。

以下是语法:

static IEnumerable<string> Message(){
   yield return "Hello!";
   yield return "Hello!";
}
Can be replaced by IAsyncEnumerable
static async IAsyncEnumerable<string> MessageAsync(){
   await Task.Delay(2000);
   yield return "Hello!";
   await Task.Delay(2000);
   yield return "Hello!";
}

Example

的翻译为:

示例

class Program{
   public static async Task Main(){
      await foreach (var item in MessageAsync()){
         System.Console.WriteLine(item);
      }
      Console.ReadLine();
   }
   static async IAsyncEnumerable<string> MessageAsync(){
      await Task.Delay(2000);
      yield return "Hello!";
      await Task.Delay(2000);
      yield return "Hello!";
   }
}

输出

Hello!
Hello!

相关推荐