何时使用Observable.FromEventPattern而不是Observable.FromEvent?

时间:2011-06-24 04:41:30

标签: c# system.reactive

我们有一个客户端正在呼叫TIBCO EMS队列并正在连接这样的事件:

var msgConsumer = _session.CreateConsumer(responseQueue);
var response = Observable.FromEvent<EMSMessageHandler,EMSMessageEventArgs>
            (h => msgConsumer.MessageHandler += h, h => msgConsumer.MessageHandler -= h)
            .Where(arg => arg.Message.CorrelationID == message.MessageID);

当我调用response.Subscribe(...)时,我收到System.ArgumentException“绑定到目标方法的错误。”

我可以使它与Observable.FromEventPattern<EMSMessageEventArgs>(msgConsumer, "MessageHandler")一起使用但是它将事件作为字符串而不是干净。

我还有IObservable<EventPattern<EMSMessageEventArgs>>而不是IObservable<EMSMessageEventArgs>

我想了解的是:我应该何时使用FromEvent而不是FromEventPattern?这似乎有点反复试验。

3 个答案:

答案 0 :(得分:63)

“使用FromEvent结构中的事件看起来不像.NET事件模式(即不基于发送者,事件参数),并使用FromEventPattern作为基于模式的事件。” - Bart De Smet (Rx team)

答案 1 :(得分:18)

为了进一步详细说明,您通常可以根据您要观察的类中使用的事件类型来确定何时选择FromEvent vs FromEventPattern之一。当您的活动属于EventHandler类型或通用EventHandler<T>时,请使用FromEventPattern。在使用自定义非通用事件处理程序类型时使用FromEvent。 以下示例直接取自Rx wiki,其中包含许多好的示例 - 确切地说是101 of them

FromEventPattern (使用通用EventHandler)

class ObserveEvent_Generic
{
    public class SomeEventArgs : EventArgs { }
    public static event EventHandler<SomeEventArgs> GenericEvent;

    static void Main()
    {
        // To consume GenericEvent as an IObservable:
        IObservable<EventPattern<SomeEventArgs>> eventAsObservable = Observable.FromEventPattern<SomeEventArgs>(
            ev => GenericEvent += ev,
            ev => GenericEvent -= ev );
    }
}

<强> FromEvent:

class ObserveEvent_NonGeneric
{
    public class SomeEventArgs : EventArgs { }
    public delegate void SomeNonGenericEventHandler(object sender, SomeEventArgs e);
    public static event SomeNonGenericEventHandler NonGenericEvent;

    static void Main()
    {
        // To consume NonGenericEvent as an IObservable, first inspect the type of EventArgs used in the second parameter of the delegate.
        // In this case, it is SomeEventArgs.  Then, use as shown below.
        IObservable<IEvent<SomeEventArgs>> eventAsObservable = Observable.FromEvent(
            (EventHandler<SomeEventArgs> ev) => new SomeNonGenericEventHandler(ev), 
            ev => NonGenericEvent += ev,
            ev => NonGenericEvent -= ev);
    }
}

答案 2 :(得分:7)

显然新语法有所改变。当前语法如下:

// get events as observable 
var events = Observable.FromEvent<MouseButtonEventHandler, MouseEventArgs>(
    handler => MouseUp += handler, handler => MouseUp -= handler);

// subscribe to events
var subscription = events.Subscribe(args => OnMouseUp()));

// always dispose subscriptions! 
subscription.Dispose();