从C#中的事件和垃圾收集中分离匿名侦听器 [英] detaching anonymous listeners from events in C# and garbage collection

查看:119
本文介绍了从C#中的事件和垃圾收集中分离匿名侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为Dialog的类扩展了Form。在对话框中有一个文本框和一个OK按钮,当用户单击确定时,文本框的值将通过事件返回:

  public class Dialog:Form 
{
public delegate void onDialogValueReturned(object sender,DialogEventArgs e);
public event onDialogValueReturned DialogValueReturned;




OKButton.Click + =(sender,evt)=>
{
DialogEventArgs e = new DialogEventArgs();
e.Value = myTextBox.Text;
DialogValueReturned(this,e);
this.Close();
};

在我的调用形式中,我在本地方法中实例化对话框:

  private void Foo()
{
Dialog D = new Dialog(blah blah);
D.DialogValueReturned + =(dialog,evt)=>
{

//用evt.Value

做些事情;


D.ShowDialog();

$ / code>

这个对话框可能会在用户执行期间由用户实例化数十次甚至数百次



当作用域离开私有方法时,垃圾回收器是否会自动清理与对话框实例相关的所有内容,包括匿名侦听器的所有管道?



谢谢 给每个用户。如果发布者的时间长于订阅者,那么订阅者将在发布者在场时被固定在内存中。

在您的示例中,发布者仅存在于范围内您的私有方法,所以对话框和处理程序将在方法返回后的某个时间点被垃圾收集。



我建议遵守用于发布事件的dot net framework指南,它建议使用受保护的虚拟方法来调用事件。


Let's say I have a class called Dialog that extends Form. There's a textbox on the dialog and an OK button, and when the user clicks OK, the textbox value is returned via an event:

public class Dialog: Form
{
    public delegate void onDialogValueReturned(object sender, DialogEventArgs e);
    public event onDialogValueReturned DialogValueReturned;
 .
 .
 .

  OKButton.Click += (sender, evt) =>
        {
            DialogEventArgs e = new DialogEventArgs();
            e.Value =myTextBox.Text;                
            DialogValueReturned(this, e);
            this.Close();
        };

In my calling form, I'm instantiating a dialog in a local method:

  private void Foo()
  {
        Dialog D = new Dialog("blah blah");
        D.DialogValueReturned += (dialog, evt) =>
            {

               //do something with evt.Value

            };


        D.ShowDialog();
   }

This dialog might be instantiated dozens or even hundreds of times by the user during the course of the day.

Does the garbage collector automatically clean up everything relating to the dialog instance when scope leaves the private method, including all of the plumbing for the anonymous listener?

Thanks

解决方案

The publisher of an event retains a strong reference to each subscriber. If the publisher is longer lived than the subscribers, then the subscribers will be pinned in memory while the publisher is present.

In your example, the publisher only exists within the scope of your private method, so both the dialog and the handler will be garbage collected at some point after the method returns.

I would recommend complying with the dot net framework guidelines for publishing an event, which suggests using a protected virtual method to invoke the events.

这篇关于从C#中的事件和垃圾收集中分离匿名侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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