什么是从C#事件unsibscribe有道? [英] What's a proper way to unsibscribe from events in c#?

查看:235
本文介绍了什么是从C#事件unsibscribe有道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这是我从其他类订阅事件的模型类。我想订阅,并在各班正确取消订阅。

I have a model class with an event which I subscribe from other classes. I want to subscribe and un-subscribe in each class correctly.


  • 首先我要保证在MyClass的我unsibscribe只有一次甚至代码是在一些方法。

  • 其次还有其他类除了MyClass的女巫使用OnMyEvent所以我不想无意中从类事件unsibscribe。

  • First I want to guarantee that in MyClass I unsibscribe only once even that code is in few methods.
  • Second there are other classes except MyClass witch use OnMyEvent so I don't want to unintentionally unsibscribe from the event in the class.

 MyClass(IModel model)
{
  _model = model;
  _model.OnMyEvent +=EventHandle;
}
Close()
{
 _model.OnMyEvent -=EventHandle;
} 
Disconnect()
{
 //I want to check if OnMyEvent has already unsibscribed
 //Moreover OnMyEvent is used in other classes and
 //I don't want to mess up with it here 
 _model.OnMyEvent -=EventHandle;
}


推荐答案

如果你只的订阅的一次,没关系的如何的取消订阅很多次 - 取消订阅,当你没有订阅无糖运。同样,事件API的整个问题是,你的不能的意外取消其他订阅(或者其他类型的,或同类型的其他实例)。

If you only subscribe once, it doesn't matter how many times you unsubscribe - unsubscribing when you don't have a subscription is a no-op. Equally, the entire point of the event API is that you can't accidentally unsubscribe other subscriptions (either other types, or other instances of the same type).

因此,如要精细,但它可能是值得移动两个呼叫处理这一单一方法的代码。这可能是矫枉过正,但。

As such, the code as shown should be fine, although it might be worth moving the two calls to a single method that handles this. That might be overkill, though.

另外,如果你的类型是的IDisposable ,确定它在调用代码路径(通过调用关闭()大概)。

Also, if your type is IDisposable, make sure it gets called in that code-path too (presumably by calling Close()).

这篇关于什么是从C#事件unsibscribe有道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆