我应该取消订阅事件吗? [英] Should I unsubscribe from events?

查看:28
本文介绍了我应该取消订阅事件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个关于事件的问题:

I have 3 questions concerning events:

  1. 我是否应该始终取消订阅已订阅的事件?
  2. 如果我不这样做会怎样?
  3. 在下面的示例中,您将如何取消订阅已订阅的事件?

例如我有这个代码:

Ctor:目的:用于数据库属性更新

Ctor: Purpose: For database property updates

this.PropertyChanged += (o, e) =>
{
    switch (e.PropertyName)
    {
        case "FirstName": break;
        case "LastName": break;
    }
};

和这个:目的:对于 GUI 绑定,将模型包装到视图模型中

and this: Purpose: For GUI-binding wrap the model into viewmodels

ObservableCollection<Period> periods = _lpRepo.GetDailyLessonPlanner(data.DailyDate);
PeriodListViewModel = new ObservableCollection<PeriodViewModel>();

foreach (Period period in periods)
{
    PeriodViewModel periodViewModel = new PeriodViewModel(period,_lpRepo);
    foreach (DocumentListViewModel documentListViewModel in periodViewModel.DocumentViewModelList)
    {
        documentListViewModel.DeleteDocumentDelegate += new Action<List<Document>>(OnDeleteDocument);
        documentListViewModel.AddDocumentDelegate += new Action(OnAddDocument);
        documentListViewModel.OpenDocumentDelegate += new Action<int, string>(OnOpenDocument);
    }
    PeriodListViewModel.Add(periodViewModel);
}

推荐答案

1) 视情况而定.通常这是一个好主意,但在某些典型情况下您不需要这样做.基本上,如果您确定订阅对象的生命周期比事件源长,则应该取消订阅,否则会创建不必要的引用.

1) It depends. Usually it's a good idea, but there are typical cases where you don't need to. Basically, if you are sure that the subscribing object is going to outlive the event source, you ought to unsubscribe, otherwise this would create an unnecessary reference.

然而,如果您的对象订阅了它自己的事件,如下所示:

If however your object is subscribing to its own events, like in the following:

<Window Loaded="self_Loaded" ...>...</Window>

——那你就不必了.

2) 订阅事件会额外引用订阅对象.因此,如果您不取消订阅,您的对象可能会通过此引用保持活动状态,从而有效地造成内存泄漏.通过取消订阅,您将删除该引用.请注意,在自行订阅的情况下,不会出现此问题.

2) Subscribing to an event makes additional reference to the subscribing object. So if you don't unsubscribe, your object might be kept alive by this reference, making effectively a memory leak. By unsubscribing you are removing that reference. Note that in the case of self-subscription the problem doesn't arise.

3) 你可以这样做:

this.PropertyChanged += PropertyChangedHandler;
...
this.PropertyChanged -= PropertyChangedHandler;

哪里

void PropertyChangedHandler(object o, PropertyChangedEventArgs e)
{
    switch (e.PropertyName)
    {
        case "FirstName": break;
        case "LastName": break;
    }
}

这篇关于我应该取消订阅事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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