且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

异步迭代器任务<IEnumerable<T>>

更新时间:2022-05-05 15:39:10

听起来你可能真正想要的是 IObservable<T>,有点像基于推送的异步 IEnumerable<T>代码>.查看 Reactive Extensions,又名 Rx(在 MIT 许可的代码)(无从属关系)了解大量方法与 IObservable<T> 一起工作,使其像 LINQ-to-Objects 等一样工作.

It sounds like what you may really be looking for is something like IObservable<T>, which is sort of like a push-based asynchronous IEnumerable<T>. See Reactive Extensions, a.k.a. Rx (code licensed under MIT) (no affiliation) for a huge host of methods that work with IObservable<T> to make it work like LINQ-to-Objects and more.

IEnumerable<T> 的问题在于,没有什么可以真正使枚举本身异步.如果您不想添加对 Rx 的依赖(这确实是 IObservable<T> 大放异彩的原因),这个替代方案可能适合您:

The problem with IEnumerable<T> is that there's nothing that really makes the enumeration itself asynchronous. If you don't want to add a dependency on Rx (which is really what makes IObservable<T> shine), this alternative might work for you:

public async Task<IEnumerable<char>> TestAsync(string testString)
{
    return GetChars(testString);
}

private static IEnumerable<char> GetChars(string testString)
{
    foreach (char c in testString.ToCharArray())
    {
        // do other work
        yield return c;
    }
}

虽然我想指出的是,在不知道异步实际上做什么的情况下,可能有更好的方法来实现您的目标.您发布的所有代码实际上都不会异步执行任何操作,而且我真的不知道 //do other work 中的任何内容是否是异步的(在这种情况下,这不是您底层的解决方案问题虽然它会让你的代码编译).

though I'd like to point out that without knowing what's actually being done asynchronously, there may be a much better way to accomplish your goals. None of the code you posted will actually do anything asynchronously, and I don't really know if anything in // do other work is asynchronous (in which case, this isn't a solution to your underlying problem though it will make your code compile).