Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
hi all,

C#
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);
  }
}


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
Posted
Updated 29-Jun-11 17:54pm
v8
Comments
Sergey Alexandrovich Kryukov 29-Jun-11 1:41am    
Where is the code with using "img" with event? Event indeed affect the lifetime, but you did not show this case. Please see my answer, in particular, the part about anonymous methods.
--SA
Silju MC 29-Jun-11 5:01am    
:-) thanks for your reply. I just updated the code in my question. Can you plz go through it and tell me if anything wrong in that code...
Silju MC 29-Jun-11 5:06am    
:-) the code is working well... and i just want to know is there any chance to an exception. I think the object "img" is released by GC before getting the WebClient response may produce an exception... i'm waiting for your feedback... Thanks a lot in advance
Sergey Alexandrovich Kryukov 29-Jun-11 6:33am    
I'm afraid to be wrong; it looks a bit more complicated then it has to be; maybe you need to explain you goal more. But it's ok.

To the main point: I explained in my answer that .NET will not allow releasing img to happen too soon. The fact that the handler uses the variable will defer the process of scheduling this variable for destruction. (See also my past answer about closures, referenced.) .NET keeps things under control, don't worry.
--SA
Silju MC 29-Jun-11 7:02am    
Thanks a lot for your information... I read your solution. It helps me a lot. My 5 to your answer :-)

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
 
Share this answer
 
v2
Comments
Manfred Rudolf Bihy 29-Jun-11 5:44am    
5!
(I'm not sure though if the image is really lost, as the images DownLoadCompletet event handler will have the image passed to it.)
Sergey Alexandrovich Kryukov 29-Jun-11 6:35am    
OP fixed the code, posted in question, please see. I was answering before it was done.
--SA
Manfred Rudolf Bihy 29-Jun-11 6:51am    
Check!
Sergey Alexandrovich Kryukov 29-Jun-11 11:58am    
Thank you for editing my answer.
--SA
Tarun.K.S 29-Jun-11 6:02am    
Good answer. 5
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.
 
Share this answer
 
Comments
Tarun.K.S 29-Jun-11 6:03am    
Hmm quite likely to happen.
Silju MC 30-Jun-11 5:11am    
Thanks :-)
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
 
Share this answer
 
Comments
Tarun.K.S 29-Jun-11 6:03am    
Right.
Silju MC 30-Jun-11 5:10am    
Thanks for your information... :-) 5+

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900