且构网

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

异步迭代任务<&IEnumerable的LT; T>>

更新时间:2021-12-02 21:30:56

这听起来像你可能真的要寻找的是类似的&的IObservable LT; T> ,这有点像一个基于推送的异步的IEnumerable< T&取代。请参见无扩展,微软开放技术又名接收(code Apache-下许可2.0)(没有隶属关系)为与的IObservable&LT工作方法,一个巨大的主机; T>使它象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).