变量的寿命 [英] life time of a variable

查看:88
本文介绍了变量的寿命的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

hi all,

class MyClass
{
  void fn()
  {
    Image img = new Image();
    //register event
    img .OnImageDownloadingCompleted += new ImageDownloadCompletedEvent(MyEventCaptured);
    img.DownloadImage();    
  }

  void MyEventCaptured(Object o, EventArgs e) 
  {
    //...
  }
}

public delegate void ImageDownloadCompletedEvent(object sender, EventArgs e);
class Image
{
  WebClient wc;
  public event ImageDownloadCompletedEvent OnImageDownloadingCompleted;

  public void DownloadImage()
  {
    Uri uri = new Uri("url of the image");
    wc = new WebClient();
    wc .OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
    wc .OpenReadAsync(uri, _webClient); //Asyncronous web client request to download an image
  }

  void  wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
  {
    //Fire my own custom event
    OnImageDownloadingCompleted(this,null);
  }
}



在此代码段中,下载图像是一个异步调用,下载过程完成后,我从Image类中触发了一个事件.我在MyClass中捕获了该事件.

我在函数fn()中创建了Image类的对象,并注册了该事件.执行完函数fn()后,我从Image类获得了事件.

我的问题是……对象"img"的寿命是多少?何时由GC释放?我发现在完成fn()执行之后,该事件是从"img"触发的.如果对象"img"的生存期结束,则如何触发该事件...?

在此先感谢



In this code snippet, downloading image is an asynchronous call and I fired an event from the Image class when the download process is completed. and i capture the event in MyClass.

I created the object of Image class in function fn() and i register the event. After executing the function fn() i got the event from Image class.

My question is... what is the life time of object ''img''and when it will be released by GC? I found that the event is fired from ''img'' after completing the execution of fn(). If the life time of object ''img'' ends how it fires the event...?

Thanks in advance

推荐答案

不要混淆生命周期和作用域.

变量img的范围是方法fn.从这种方法的代码中,可以看出它是完全没有用的.您下载图像并松开对该图像的引用.

终生是一件更复杂的事情.这是一个参考对象.当引用在当前运行的代码的任何部分都变得不可访问时,该对象将标记为垃圾回收.但是,根据垃圾收集器(GC)使用的内部算法,破坏本身会在一段时间后发生.如果编写析构函数,则可以检测到这一刻.但是,除非明确调用System.GC.Collect,否则您无法控制此时间点.根据经验,不建议这样做,除非您必须释放一些非托管资源,否则您也无需编写析构函数.

有人会说,只有当代码超出范围时,局部变量引用的对象才变得不可访问.错了!
匿名方法的存在使这一点变得更加复杂.在匿名方法中使用局部变量可以延长其寿命.这称为关闭,请参见 http://en.wikipedia.org/wiki/Closure_ (computer_science) [ ^ ].

请查看我过去的答案以获取解释:
创建新线程的循环会出现问题 [ ^ ],
什么是C#中的匿名类型? [ ^ ].

—SA
Don''t mix up lifetime and scope.

The scope of the variable img is the method fn. From the code of this method one can see it''s completely useless. You download the image and loose the reference to it.

Lifetime is a bit more complex matter. This is a reference object. When a reference becomes inaccessible in any part of currently running code, the object is marked for garbage collection. However, the destruction itself happens some time later, according to an internal algorithm used by the Garbage Collector (GC). You can detect this moment if you write a destructor. However, you cannot control this point in time unless you explicitly call System.GC.Collect. As a rule of thumb, doing this is not recommended and you also don''t need to write destructors unless you have to release some unmanaged resources.

One would say that the object referenced by a local variable only becomes inaccessible when the code goes out of the scope. Wrong!
The existence of anonymous methods makes this even more complex. Using a local variable in an anonymous method prolongs its life time. This is called a closure, see http://en.wikipedia.org/wiki/Closure_(computer_science)[^].

Please see my past answers for the explanation:
Looping for creating new thread give some problem[^],
What are Anonymous Types in C#?[^].

—SA


对象仍然存在,即使它已经超出范围.垃圾收集会随时处理. WebClient幸运地在此之前调用wc_OpenReadCompleted(),并从那里触发了您自己的事件.我怀疑这并不完全安全.当垃圾收集器在加载完成之前发出警告时,您可能会得到一个漂亮的异常.
The object still exists, even when it has gone out of scope. The garbage collection will take care of it any time. The WebClient luckily calls wc_OpenReadCompleted() before that happens and from there your own event is fired. I suspect that this is not entirely safe. You will probably get a beautiful exception when the garbage collector strikes before loading is finished.


对象生存期由垃圾收集器决定,除非您编写自己的垃圾收集和完成操作.

用简单的话来说,在这个例子中,它直到GC清除之前仍然有效.

http://msdn.microsoft.com/en-us/magazine/cc163316.aspx [ ^ ]

http://darkcodingzone.blogspot.com/2008/11/basics- of-object-lifetime-in-cnet.html [ ^ ]

欢呼
巴拉吉(Balaji)
Objects lifetime is decided by the Garbage Collector, unless you write your own Garbage collection and finalization.

In simple words, for this example, it will still be alive until the GC works to clear it off.

http://msdn.microsoft.com/en-us/magazine/cc163316.aspx[^]

http://darkcodingzone.blogspot.com/2008/11/basics-of-object-lifetime-in-cnet.html[^]

cheers
Balaji


这篇关于变量的寿命的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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