我们有一个客户端正在调用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
?这似乎有点试错。
"对结构上看起来不像.NET事件模式的事件使用FromEvent(即不基于发送方、事件参数),对基于模式的事件则使用FromEventPattern。"-Bart De Smet(Rx团队)
为了进一步详细说明这一点,您通常可以根据您试图观察的类中使用的事件类型来确定何时选择FromEvent
与FromEventPattern
之一。当事件类型为EventHandler
或通用EventHandler<T>
时,请使用FromEventPattern
。当您使用自定义的非通用事件处理程序类型时,请使用FromEvent
。下面的例子是直接从Rx wiki中提取的,其中有很多好的例子——确切地说是101个。
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 );
}
}
来自事件:
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);
}
}
显然,新语法发生了一些变化。当前语法如下:
// 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();