当使用的IEnumerable VS的IObservable?IEnumerable、VS、IObservable

2023-09-03 16:15:54 作者:风雨哈佛路

如何建立一个方法是否应该返回的IEnumerable< T> 的IObservable< T>

How do you establish whether or not a method should return IEnumerable<T> or IObservable<T>?

为什么我会选择一种模式比其他?

Why would I choose one paradigm over the other?

推荐答案

的IEnumerable&LT; T&GT; 您重复地从 T 的序列拉

Types

IEnumerable<T> You repeatedly "pull" from a sequence of T's

T 的的序列被推你 A sequence of T's is being "pushed" at you

为什么我会选择一种模式比其他?

Why would I choose one paradigm over the other?

您通常的不的选择一模式比其他。通常一个突出的自然是正确的选择,而另一个不作任何意义。

You typically don't "choose" one paradigm over the other. Usually one stands out naturally as the correct choice, with the other one not making any sense.

考虑下面的例子:

一个巨大的CSV文本文件都有每行的项目,要处理他们一次,而无需加载整个文件到内存一次:的IEnumerable&LT;列表&LT;字符串&GT; &GT;

您运行的是HTTP Web服务器:的IObservable&LT; WebRequest的&GT;

You are running an HTTP web server: IObservable<WebRequest>

您想做得到广度优先的方式树数据结构的节点:的IEnumerable&LT;节点&GT;

You want to do get the nodes of a tree data structure in a breadth-first manner: IEnumerable<Node>

正在响应用户界面按钮点击:的IObservable&LT;点击&GT;

You are responding to user interface button clicks: IObservable<Click>

在每个例子中(尤其是的IObservable&LT; T&GT; 的情况下),它只是没有意义使用其他类型的

In each of these examples (especially the IObservable<T> cases), it just wouldn't make sense to use the other type.

如果事情是自然的的IObservable&LT; T&GT; 但是你要处理它,仿佛它是一个的IEnumerable&LT; T&GT; ,你可以做,用这种方法:

If something is naturally an IObservable<T> but you want to process it as if it were an IEnumerable<T>, you can do that with this method:

IEnumerable<T> Observable.ToEnumerable(this IObservable<T>)

T 被推由的IObservable&LT; T&GT; ,它被发送到一个队列。 当你试图拉一个 T 的IEnumerable&LT的; T&GT; ,它阻止,直到队列不空,则出队。

When a T gets "pushed" by the IObservable<T>, it gets sent into a queue. When you try to "pull" a T out of the IEnumerable<T>, it blocks until the queue isn't empty, then dequeues.

如果事情是自然的的IEnumerable&LT; T&GT; 但是你要处理它,仿佛它是一个的IObservable&LT; T&GT; ,你可以做,用这种方法:

If something is naturally an IEnumerable<T> but you want to process it as if it were an IObservable<T>, you can do that with this method:

IObservable<T> Observable.ToObservable(this IEnumerable<T>)

从.NET线程池将反复尝试,以拉一个线程 T 的IEnumerable&LT; T&GT; 。 在每次拉一个 T ,它通过推它在你的时间的IObservable&LT; T&GT;

A thread from the .NET thread pool will repeatedly try to "pull" a T from the IEnumerable<T>. Each time it "pulls" a T, it "pushes" it at you via the IObservable<T>.