473,699 Members | 2,752 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"Simple" animation in C# --> memory leaks???

Hello all,

I am trying to write a "simple" animation using C#, and I've tried many
things but nothing seems to work for me without leaking memory. Here's
a very simple piece of code that uses a timer to set the image of a
label from an ImageList every 100ms or so. This is what was being used
when I inherited this piece of code, and I thought it was OK, until I
changed the size of the label to do animation on a larger piece of
screen real-estate.

-----------------------------------------
public void Timer_Tick(obje ct sender, EventArgs e)
{
if (isAnimating)
{
pic_index = ++pic_index % 18;
this.label1.Ima geIndex = pic_index;
}
else
{
this.timer1.Ena bled = false;
}
}

-----------------------------------------

The form has a start and stop button, and the label. The imagelist has
18 images in it. I start it and it runs and leaks memory like a sieve!
The "in memory" footprint will shrink if I minimize the app, but we're
running on an embedded PC and there is NO virtual memory available, so
we are running full screen all the time.

I've tried other approaches such as double buffering, and that leaks
about 4k bytes / second at 10 refreshes per second. Here's the "tick"
method from that attempt:

-----------------------------------------
public void Timer_Tick(obje ct sender, EventArgs e)
{
if (isAnimating)
{
pic_index = ++pic_index % 18;
Graphics AnimG = screen.getGraph ics(); // gets an offscreen "copy"
screen.erase();
spriteArray[pic_index].draw(AnimG); // draw to the copy
screen.flip(); // blt
AnimG = null;
}
else
{
this.timer1.Ena bled = false;
}
}
-----------------------------------------

The imagelist example acts like it's "copying" the image out of the
image list and storing it into some permanent (semi-permanent) data
structure someplace and keeping a strong reference to it. I don't even
have a theory as to what the double-buffering sample is doing, how it
could be leaking 4k bytes per second, any new objects created in the
tick method are destroyed at the end of it! In that method, I have 18
"sprites" where one gets painted to the buffer each tick and the buffer
is blt-d to the screen on a panel. That's about as simple as you can
make it.

The only thing I can figure is I'm using the timer wrong - somehow.
I've copied samples off the 'net, I don't "start" the timer anymore,
just enable or disable it.

Anybody have any clues as to what I've done wrong? I've done
animations for years in Java, and NEVER seen anything like this. I
"stumbled" on the memory leak issue because we ran our embedded PC out
of memory so fast it (the app not the PC) crashed in about 30s.

I'm frustrated and developing a VERY bad taste for C#.

Thanks in advance.

Nov 17 '05 #1
8 3688
I haven't done enough coding with the compact framework to be sure what
is in it, but I feel that some calls to the garbage collector could
help. I say this because you say the memory issue is solved with
minimizing. In regular C# coding you can invoke the garbage collector
with the code GC.Collect(). So try and see if that is in the CF or not
and if so see what happens when you call it after every redraw.

Also, as for the timer, I prefer to use Thread.Sleep() for timed
events. It just seems to be more solid. Hope this helps ~ Justin

Nov 17 '05 #2
Thanks Justin,

That does seem to work. But why on earth does it require an _explicit_
call to GC in order to recover memory, and why does the app happily
crash before at least trying to run GC?

Microsoft - are you listening? Is this half-baked or what?

-Scotty

Nov 17 '05 #3


"Beam_Us_Up_Sco tty" wrote:
Thanks Justin,

That does seem to work. But why on earth does it require an _explicit_
call to GC in order to recover memory, and why does the app happily
crash before at least trying to run GC?

Microsoft - are you listening? Is this half-baked or what?


MS product feedback and bug reporting site.

http://lab.msdn.microsoft.com/produc...k/default.aspx

Not keeping enough memory free to allow the GC to collect without requesting
more from the system does appear to be a bug, probably from a missed test
case.
Nov 17 '05 #4
Justin wrote:
Also, as for the timer, I prefer to use Thread.Sleep() for timed
events. It just seems to be more solid. Hope this helps ~ Justin


Note that Thread.Sleep() will 'sleep' the current thread, but it also
allows other threads to work. I guess this is why you find it more
'solid' because calling it will not impact other work being done on
other threads in the process. Indeed, if you want to 'switch' to another
thread in your process on a single processor machine you can call
Thread.Sleep(0) .

Richard
--
http://www.grimes.demon.co.uk/workshops/fusionWS.htm
http://www.grimes.demon.co.uk/workshops/securityWS.htm
Nov 17 '05 #5
Beam_Us_Up_Scot ty wrote:
-----------------------------------------
public void Timer_Tick(obje ct sender, EventArgs e)
{
if (isAnimating)
{
pic_index = ++pic_index % 18;
Graphics AnimG = screen.getGraph ics(); // gets an offscreen "copy"
screen.erase();
What is this screen object? How is getGraphics implemented?

I suspect you are doing something like a call to Graphics.FromHW ND() or
FromImage(). If you implement it using one of these methods (or similar)
then you must release the graphics object after you have finished using
it, see below...
spriteArray[pic_index].draw(AnimG); // draw to the copy
screen.flip(); // blt
Anim.Dispose();
AnimG = null;
Doing this will just mark the object as being available for garbage
collection sometime in the future, but you have no idea when that will
be. The graphics object's finaliser effectively calls Dispose(). Calling
Dispose explicitly will clean up the resources immediately.

Better still, the device context will not change during the animation,
so you do not need to create a new Graphics object for each tick.
Instead, create it once and then cache it. Therefore you
screen.getGraph ics will return the cached Graphics object. In this case
DO NOT Dispose the Graphics object in the tick method.
I'm frustrated and developing a VERY bad taste for C#.


To be honest, this has nothing to do with C#, it is an issue with
non-deterministic finalization, which is a .NET issue, and anyway, Java
has just the same problems.

Richard
--
http://www.grimes.demon.co.uk/workshops/fusionWS.htm
http://www.grimes.demon.co.uk/workshops/securityWS.htm
Nov 17 '05 #6

"Justin" <ju***********@ gmail.com> wrote in message
news:11******** *************@g 49g2000cwa.goog legroups.com...
I haven't done enough coding with the compact framework to be sure what
is in it, but I feel that some calls to the garbage collector could
help. I say this because you say the memory issue is solved with
minimizing. In regular C# coding you can invoke the garbage collector
with the code GC.Collect(). So try and see if that is in the CF or not
and if so see what happens when you call it after every redraw.

Also, as for the timer, I prefer to use Thread.Sleep() for timed
events. It just seems to be more solid. Hope this helps ~ Justin

You should never call GC.Collect on disposable objects, Dispose them of when
done with them.

Willy.
Nov 17 '05 #7

"Beam_Us_Up_Sco tty" <sc************ **@swisslog.com > wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Thanks Justin,

That does seem to work. But why on earth does it require an _explicit_
call to GC in order to recover memory, and why does the app happily
crash before at least trying to run GC?

Microsoft - are you listening? Is this half-baked or what?

-Scotty


Images are unmanaged resources (they are loaded in the process heap not in
the GC heap), so you need to call Dispose to release them, the GC has
nothing to do with unmanaged memory. When calling GC.Collect() you force the
finalizer to run, and the finalizer will call Finally" on the Graphics
object and this one will release the unmanaged memory, but you shouldn't do
that, call Dispose or use a using statement block like this:.

pic_index = ++pic_index % 18;
using(Graphics AnimG = screen.getGraph ics())
{
screen.erase();
spriteArray[pic_index].draw(AnimG); // draw to the copy
screen.flip(); // blt
// no need to set AnimG to nul here, this is taken care of by the Finaly
method.
}
Willy.
Nov 17 '05 #8

"Dan Neely" <Da******@discu ssions.microsof t.com> wrote in message
news:5E******** *************** ***********@mic rosoft.com...


"Beam_Us_Up_Sco tty" wrote:
Thanks Justin,

That does seem to work. But why on earth does it require an _explicit_
call to GC in order to recover memory, and why does the app happily
crash before at least trying to run GC?

Microsoft - are you listening? Is this half-baked or what?


MS product feedback and bug reporting site.

http://lab.msdn.microsoft.com/produc...k/default.aspx

Not keeping enough memory free to allow the GC to collect without
requesting
more from the system does appear to be a bug, probably from a missed test
case.


Not sure where you get this from, Graphic objects do wrap unmanaged
resources (memory and GDI handles) and therefore implements the Dispose
pattern, failing to call Dispose in a timely fashion (say when done with it)
will result in a program failure as you will exhaust the GDI objects handles
(these are limited unmanaged resources) available to the process, the GC
will never kick in here because it has no knowledge of such resources.
Willy.
Nov 17 '05 #9

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

Similar topics

4
16686
by: Maurice | last post by:
Hi there, I'm experiencing big memory problems on my webserver. First on an old RedHat 7.2 system, now on an other fresh installed Suse 8.2 system: Linux version 2.4.20-4GB (root@Pentium.suse.de) (gcc version 3.3 20030226 (prerelease) (SuSE Linux)) #1 Wed Aug 6 18:26:21 UTC 2003 Apache 1.3.27-41 PHP 4.3.1-52 MySQL 3.23.55-20
2
4953
by: Generic Usenet Account | last post by:
I have been using STL for a long time now, without any problems. Recently we generated a purification report on our software using Rational Purify, and we found some memory leaks. My colleague claims that some of the memory leaks are due to the fact that "STL is wrought with memory leaks". Of course I disagree. I think that there are no "inherent leaks" with STL, but if used improperly, leaks will occur. One common source of leak that...
3
9239
by: laniik | last post by:
Hi. I was wondering if there were any known leaks using STL vectors. Also, I was wondering if I have to do any sort of deleting or memory clearing when im done with the vector, or will they be removed correctly when they leave scope? the only memory issue i know is that if i use: vector.clear() on objects that have memory allocated within them, then it will cause
0
3902
by: Frank Lopez | last post by:
Does anyone know if Microsoft generated a whitepaper on this topic? Does anyone know what the solution is? (meaning, eliminate the leak problem -- I am seeing three memory leaks from dllmodul.cpp(102) similar to what is mentioned below)... I am calling MFC as part of unmanaged code used by the managed code. +--------
10
418
by: darkStar_e2 | last post by:
Hi guys. I have an applications which unfortunately eating up all the computer resources. the this is that it is not releasing the resources (memory) that it has eaten after it was closed... how do i handle this...
4
5715
by: ali.jan | last post by:
Hi, It is trivial to load an assembly in a new Application Domain. Is there any way of loading an assembly in a new process? I tried using the Process class like this: Process p = new Process() p.StartInfo.FileName = mStartupFile p.StartInfo.UseShellExecute = False
3
5322
by: Jim Land | last post by:
Jack Slocum claims here http://www.jackslocum.com/yui/2006/10/02/3-easy-steps-to-avoid-javascript- memory-leaks/ that "almost every site you visit that uses JavaScript is leaking memory". Anybody know anything about this? Does *Javascript* leak memeory, or does the *browser* leak memory?
6
5568
by: nmehring | last post by:
I have an MFC app with 2000 users. I have one user that experiences a crash in our software anywhere from 1 to 5 times a week when opening a particular module. No other users have reported this particular crash so I don't think anyone else is experiencing it but I know other users are doing exactly what she is doing because it is our most popular module. I have analyzed the dmp files from several of this user's crashes using windbg...
11
4229
by: dhtml | last post by:
(originally mis-posted on m.p.s.jscript...) I've just closed all windows in Firefox and its using 244MB of memory. I have no idea why. I had GMail open, a page from unicode, the CLJ FAQ. I've noticed that createElement leaks. It's obvious with form controls because the form keeps the control name as a property. Example:
0
9174
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9035
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8914
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8884
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7751
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6534
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5875
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4629
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2009
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.