What best practices for cleaning up event handler references?

后端 未结 6 1641
一个人的身影
一个人的身影 2020-12-04 15:52

Often I find myself writing code like this:

        if (Session != null)
        {
            Session.KillAllProcesses();
            Session.AllUnitsReady          


        
6条回答
  •  盖世英雄少女心
    2020-12-04 16:06

    My preference is to manage lifetime with a disposable. Rx includes some disposable extensions which let you do the following:

    Disposable.Create(() => {
                    this.ViewModel.Selection.CollectionChanged -= SelectionChanged;
                })
    

    If you then store this in some kind of GroupDisposable thats lifetimed to the correct scope then you are all set.

    If you aren't managing lifetime with disposables and scopes then definitely worth investigating as its becoming a very pervasive pattern in .net.

提交回复
热议问题