473,406 Members | 2,352 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Memory Leak in C# 2.0 W/ Anonymous Delegates?

I believe I ran into an interesting way to create memory leaks in C# 2.0
using anymous delegates. Here is a sample of the code in question.

private void Handle_Event(object sender, EventArgs e)
{
Timer timer = new Timer();
timer.Interval = 10000;
NotifyForm notifyForm = new notifyForm();
notifyForm.Show();
timer.Tick += delegate(object timerSender, EventArgs tArgs)
{
notifyForm.Close();
notifyForm.Dispose();
timer.Stop();
};
timer.Start();
}

The above code is responding to an event, displaying a Form to notify the
user of the completed event and closing the Form in 10 seconds. The
potential issue I see is I assign an anonymous delegate into the timer's Tick
event. The timer's Tick event now has a reference to my anonymous delegate.
According to Anders Heilsbergs book on C# 2.0 the timer reference will now be
captured and will not be released until after the anonymous delegate has been
garbage collected, but in the above example the anonymous delegate cannot be
collected , because the Timer's Tick event has a reference to it. Is this
analysis of this code correct? If so what suggestions do you have to get
around this. I have my own suggestion, it goes something this (I really have
to credit my co-worker Mike for this suggestion):

private void Handle_Event(object sender, EventArgs e)
{
Timer timer = new Timer();
timer.Interval = 10000;
NotifyForm notifyForm = new notifyForm();
notifyForm.Show();
//Initializing the handler variable to null allows it to be accessed
inside of the
//anonymous delegate.
EventHandler handler = null;
handler = delegate(object timerSender, EventArgs tArgs)
{
notifyForm.Close();
notifyForm.Dispose();
timer.Stop();
timer.Tick -= handler;
} ;
timer.Tick += handler;
timer.Start();
}

The idea in the above example being that the anonymous delegate is assigned
into a local variable which can be accessed inside of the anonymous delegate.
By doing this I can unsubscribe from the Tick event allowing the delegate to
garbage collected, and consequently the Timer instance can also be garbage
collected. Does this solve the issues of the memory leak? Is there a better
way to solve this issue? Thank you.

Nov 17 '05 #1
3 8781

"anonymous" <an*******@discussions.microsoft.com> wrote in message
news:24**********************************@microsof t.com...
I believe I ran into an interesting way to create memory leaks in C# 2.0
using anymous delegates. Here is a sample of the code in question.

private void Handle_Event(object sender, EventArgs e)
{
Timer timer = new Timer();
timer.Interval = 10000;
NotifyForm notifyForm = new notifyForm();
notifyForm.Show();
timer.Tick += delegate(object timerSender, EventArgs tArgs)
{
notifyForm.Close();
notifyForm.Dispose();
timer.Stop();
};
timer.Start();
}

The above code is responding to an event, displaying a Form to notify the
user of the completed event and closing the Form in 10 seconds. The
potential issue I see is I assign an anonymous delegate into the timer's
Tick
event. The timer's Tick event now has a reference to my anonymous
delegate.
According to Anders Heilsbergs book on C# 2.0 the timer reference will now
be
captured and will not be released until after the anonymous delegate has
been
garbage collected, but in the above example the anonymous delegate cannot
be
collected , because the Timer's Tick event has a reference to it. Is this
analysis of this code correct? If so what suggestions do you have to get
around this. I have my own suggestion, it goes something this (I really
have
to credit my co-worker Mike for this suggestion):

This should collect just fine, since once the anonymous delegate is
unreferenced and it contains the only reference to the timer, then the timer
instance cannot be reached from a root and is therefore collectable as well.
Nov 17 '05 #2


"Daniel O'Connell [C# MVP]" wrote:

"anonymous" <an*******@discussions.microsoft.com> wrote in message
news:24**********************************@microsof t.com...
I believe I ran into an interesting way to create memory leaks in C# 2.0
using anymous delegates. Here is a sample of the code in question.

private void Handle_Event(object sender, EventArgs e)
{
Timer timer = new Timer();
timer.Interval = 10000;
NotifyForm notifyForm = new notifyForm();
notifyForm.Show();
timer.Tick += delegate(object timerSender, EventArgs tArgs)
{
notifyForm.Close();
notifyForm.Dispose();
timer.Stop();
};
timer.Start();
}

The above code is responding to an event, displaying a Form to notify the
user of the completed event and closing the Form in 10 seconds. The
potential issue I see is I assign an anonymous delegate into the timer's
Tick
event. The timer's Tick event now has a reference to my anonymous
delegate.
According to Anders Heilsbergs book on C# 2.0 the timer reference will now
be
captured and will not be released until after the anonymous delegate has
been
garbage collected, but in the above example the anonymous delegate cannot
be
collected , because the Timer's Tick event has a reference to it. Is this
analysis of this code correct? If so what suggestions do you have to get
around this. I have my own suggestion, it goes something this (I really
have
to credit my co-worker Mike for this suggestion):

This should collect just fine, since once the anonymous delegate is
unreferenced and it contains the only reference to the timer, then the timer
instance cannot be reached from a root and is therefore collectable as well.

You're saying that the original snippet will work just fine? If that's the
case then don't I run the risk of the timer and the delegate being garbaged
collected before the Tick event is fired, making it so my notify form remains
opened indefinately?
Nov 17 '05 #3


"anonymous" wrote:


"Daniel O'Connell [C# MVP]" wrote:

"anonymous" <an*******@discussions.microsoft.com> wrote in message
news:24**********************************@microsof t.com...
I believe I ran into an interesting way to create memory leaks in C# 2.0
using anymous delegates. Here is a sample of the code in question.

private void Handle_Event(object sender, EventArgs e)
{
Timer timer = new Timer();
timer.Interval = 10000;
NotifyForm notifyForm = new notifyForm();
notifyForm.Show();
timer.Tick += delegate(object timerSender, EventArgs tArgs)
{
notifyForm.Close();
notifyForm.Dispose();
timer.Stop();
};
timer.Start();
}

The above code is responding to an event, displaying a Form to notify the
user of the completed event and closing the Form in 10 seconds. The
potential issue I see is I assign an anonymous delegate into the timer's
Tick
event. The timer's Tick event now has a reference to my anonymous
delegate.
According to Anders Heilsbergs book on C# 2.0 the timer reference will now
be
captured and will not be released until after the anonymous delegate has
been
garbage collected, but in the above example the anonymous delegate cannot
be
collected , because the Timer's Tick event has a reference to it. Is this
analysis of this code correct? If so what suggestions do you have to get
around this. I have my own suggestion, it goes something this (I really
have
to credit my co-worker Mike for this suggestion):

This should collect just fine, since once the anonymous delegate is
unreferenced and it contains the only reference to the timer, then the timer
instance cannot be reached from a root and is therefore collectable as well.

You're saying that the original snippet will work just fine? If that's the
case then don't I run the risk of the timer and the delegate being garbaged
collected before the Tick event is fired, making it so my notify form remains
opened indefinately?

Well I peeked at the MSIL that is generated and I think I see what you're
saying. In the original snippet the timer is eligible for garbage
collection. This means that I run a serious risk of both my timer and
anonymous delegate getting garbage collected prior to the event even being
fired. The solution is to make the timer a class level member variable, not
a local variable. The reason for this is C# generates a nested class for the
anymous delegate that stores all of the referenced locals. The nested class
contains a method that has the actual implementation for the anonymous
delegate logic. That method is assigned in as a delegate to the Tick event.
Now I've got the timer referencing the instance of my anonymous delegate
nested class and the anonymous delegate instance reference the timer, but
they aren't reference by anyone else, making them eligible for garbage
collection.
Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: jong | last post by:
I have a problem with an C# application. The application is a 24x7 low volume message processing server. The server has a single thread of processing, running in a continuous loop, for each...
18
by: Dennis | last post by:
It seems that garbage collection is somewhat flawed in Netscape as the following little script can bring a machine to its knees in about an hour when run on Netstcape 7.1. I've tried freeing the...
10
by: Matt Kruse | last post by:
I'm aware of the circular reference memory leak problem with IE/closures. I'm not sure exactly how to resolve it in this situation. Also, Firefox appears to grow its memory size with the same code....
5
by: Aaron | last post by:
I just made a web app and there's some memory leak in the code. I can't use the VS.NET debugger for this. I would like to be able to see what's going on in the memory. What is the best memory...
19
by: Jon Davis | last post by:
I'm reposting this because I really need some advice. I have a web app that makes many queries to the database on every page. In order to save development effort, I've consolidated all database...
0
by: Gujju | last post by:
Hi all, At this point of time i m totally confused... and really dont know what to do... Here is my query : We have a class which we want to call in async manner and this is just a test...
4
by: Carlo | last post by:
Hi, I've a problem with a simple application and I don't know how to solve it. Create a simple vb project, create a class with some member and one event, add a timer with an interval of 10 ms....
15
by: Matt | last post by:
Hi There, Can anyone explain me the real advantages of (other than syntax) lambda expressions over anonymous delegates? advantage for one over the other. delegate int F(int a); F fLambda = a...
4
by: Frankie | last post by:
I have just gotten up to speed on what anonymous methods are (syntax, capabilities, etc), and how they can be used with /called via delegates. What I am wondering is... 1. Are they only/mostly...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.