异步迭代任务&LT;&IEnumerable的LT; T&GT;&GT; [英] Asynchronous iterator Task<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;
}
}
但是,该功能不能是迭代器块,因为任务℃的错误信息; IEnumerable的&LT;焦炭&GT;&GT;
不是一个迭代器接口类型。有没有解决的办法?
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 LT; T&GT; ,这有点像一个基于推送的异步的IEnumerable&LT; T&取代。请参见无扩展,微软开放技术又名接收(code Apache-下许可2.0)(没有隶属关系)为与的IObservable&LT工作方法,一个巨大的主机; T&GT;使它象LINQ到对象和更多的工作。
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 from Microsoft Open Technologies (code licensed under Apache-2.0) (no affiliation) for a huge host of methods that work with IObservable<T> to make it work like LINQ-to-Objects and more.
与IEnumerable的&LT的问题; T&GT;是没有什么,真正使枚举本身异步的。如果你不希望添加在RX的依赖(这是真的什么使的IObservable&LT; T&GT;光泽),这种替代可能会为你工作:
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;
}
}
但我想指出的是,不知道什么的实际被异步完成的,有可能是一个更好的方式来实现自己的目标。在code你贴实际上将做任何事情异步的,我真的不知道,如果在 //事情做其他工作的无
是异步的(在这种情况下,这不是你的潜在问题的解决方案,虽然它会让你的code编译)。
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;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!