問題描述
我正在嘗試實現一個返回迭代器的異步函數.思路如下:
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).
這篇關于異步迭代器任務<IEnumerable<T>>的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!