本文介绍了反应性框架(RX)和事件处理异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我只是在摆弄RX和学习它。我开始活动玩,并想知道如何订阅事件,以及异步处理结果的批次。请允许我用code解释:

So I'm just playing around with RX and learning it. I started playing with Events, and wanted to know how to subscribe to events, and process the results in batches asynchronously. Allow me to explain with code:

简单的类引发的事件:

public class EventRaisingClass
{
   public event EventHandler<SomeEventArgs> EventOccured;

   //some other code that raises event...
}

public class SomeEventArgs : EventArgs
{
    public SomeEventArgs(int data)
    {
        this.SomeArg = data;
    }

    public int SomeArg { get; private set; }
}

然后,我公司主营:

Then my Main:

public static void Main(string[] args)
{
    var eventRaiser = new EventRaisingClass();
    IObservable<IEvent<SomeEventArgs>> observable = 
        Observable.FromEvent<SomeEventArgs>(e => eventRaiser.EventOccured += e, e => eventRaiser.EventOccured -= e);

    IObservable<IList<IEvent<SomeEventArgs>>> bufferedEvents = observable.BufferWithCount(100);

    //how can I subscribte to bufferedEvents so that the subscription code gets called Async?
    bufferedEvents.Subscribe(list => /*do something with list of event args*/); //this happens synchrounously...

}

正如你在我的意见看,当你只需要调用订阅这样,所有的认购code发生同步。有没有出路使用RX框有订阅调用在不同的线程,每当有一个新的一批事件来工作?

As you can see in my comments, when you just call subscribe like that, all the subscription code happens synchronously. Is there a way out of the box using RX to have the Subscribe be called on different threads whenever there's a new batch of events to work on?

推荐答案

我相信你正在寻找 SubscribeOn ObserveOn ,传递一个 IScheduler 。有内置在 System.Concurrency 若干调度;他们中的一些使用任何线索是最新的,和其他人使用特定的主题。

I believe you're looking for SubscribeOn or ObserveOn, passing an IScheduler. There are several schedulers built-in under System.Concurrency; some of them use whatever thread is current, and others use specific threads.

此影片有更多的信息在调度的概念。

This video has more info on the scheduler concept.

在RX团队最近还发布了的文件,它是最接近的教程现在。

The Rx team also recently released a hands-on labs document which is the closest thing to a tutorial right now.

这篇关于反应性框架(RX)和事件处理异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 14:35