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

编程入门 行业动态 更新时间:2024-10-20 03:47:39
本文介绍了异步迭代器任务<IEnumerable<T>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试实现一个返回迭代器的异步函数.思路如下:

I’m trying to implement an asynchronous function that returns an iterator. The idea is the following:

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

但是,由于 Task

However, there is an error message that the function cannot be an iterator block because Task<IEnumerable<char>> is not an iterator interface type. Is there a solution?

推荐答案

听起来你可能真正想要的是 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).

更多推荐

异步迭代器任务&lt;IEnumerable&lt;T&gt;&gt;

本文发布于:2023-11-02 17:18:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552970.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:迭代   amp   lt   IEnumerable   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!