[英]How do you register/unregister handlers to the event used in Observable.FromEventPattern?
I'm getting an IObservable from Observable.FromEventPattern, as shown below: 我从Observable.FromEventPattern获取一个IObservable,如下所示:
SomeObject target = new SomeObject();
string eventName = "SomeEvent";
IObservable<T> obs = Observable.FromEventPattern<T>(target, eventName);
From what I understand, the FromEventPattern call will automatically generate add/remove event handlers for me. 据我了解,FromEventPattern调用将自动为我生成添加/删除事件处理程序。 But when does the handler actually get added/removed?
但是何时真正添加/删除处理程序?
I assume that the handler is added when the IObservable is subscribed to. 我假定在订阅IObservable时添加了处理程序。 Is the handler also automatically unregistered when the subscriber is disposed?
处置订户后,处理程序还会自动注销吗?
It's easy enough to just write up a simple test yourself to see when Observable
uses the add/remove handlers by simply supplying your own handlers that cause side effects: 自己编写一个简单的测试就很容易了,只需简单地提供自己的引起副作用的处理程序,就可以
Observable
在何时使用添加/删除处理程序:
var observable = Observable.FromEvent(
action => Console.WriteLine("Added"),
action => Console.WriteLine("removed"));
Console.WriteLine("Subscribing");
var subscription = observable.Subscribe(unit => { });
Console.WriteLine("disposing");
subscription.Dispose();
Console.WriteLine("done");
This prints out: 打印输出:
Subscribing Added disposing removed done
Telling us that subscribing invokes the add handler, and disposing the subscription object removes the handler. 告诉我们,订阅将调用添加处理程序,而处理预订对象将删除处理程序。
In the event that you have multiple subscriptions to the observable, then the handler will be added any time you subscribe to an observable that has no previous subscriptions, and disposing of a subscription only removes the handler if it was the last remaining subscriber. 如果您对可观察对象有多个订阅,那么只要您订阅没有先前订阅的可观察对象,就会在任何时候添加处理程序,并且仅当处理程序是最后剩余的订阅者时,处置订阅才会删除该处理程序。 This can be seen by modifying the test to create multiple subscriptions and then disposing of them all.
通过修改测试以创建多个订阅,然后将其全部处理,可以看出这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.