【问题标题】:Async and yield Keywords in c# [duplicate]c#中的异步和yield关键字[重复]
【发布时间】:2018-12-20 07:47:37
【问题描述】:
public static async ???? ReadFileLineByLineAsync(string file)
{

    using(StreamReader s = new StreamReader(file))
    {
        while (!s.EndOfStream)
            yield return await s.ReadLineAsync();
    }
}

我想写一个异步函数来逐行读取文件。这个函数的返回类型应该是什么。我将不胜感激有关此的任何建议。

【问题讨论】:

  • IEnumerable<string>?
  • afaik、asyncyield 不能一起使用。这两个关键字都会导致创建执行异步样板代码(或分别为枚举器代码)的新类,并且这些概念不能组合(至少在当前的 c# 版本中)
  • @BarrJ 不!这种问题在codereview上完全是题外话

标签: c# async-await .net-4.5 streamreader yield-return


【解决方案1】:

您可以尝试改用Reactive Linq Observable

public static IObservable<string> ReadFileLineByLineAsync(string file)
{
  return Observable.Create<string>(
    (obs, token) =>
      Task.Factory.StartNew(
        () =>
        {
          using (var s = new StreamReader(file))
          {
            while (!s.EndOfStream)
              obs.OnNext(s.ReadLine());
          }
          obs.OnCompleted();
        },
        token));
}

【讨论】:

    猜你喜欢
    • 2019-07-06
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2012-07-01
    • 2012-12-09
    • 1970-01-01
    • 2017-04-10
    • 2021-09-25
    相关资源
    最近更新 更多