S
S
Sergey Polyntsev2014-02-19 07:23:37
Programming
Sergey Polyntsev, 2014-02-19 07:23:37

How to fix a memory leak (timer is a toolbar component)?

Hello! I am writing a program, in it I use a standard component - timer. I decided to see how resources are spent on my program. It turned out that with a certain time interval the program eats up more and more memory. Created a new project to check which component is eating memory. It turned out to be a timer. Here is the line where the memory is allocated:

this.timer1.Tick += new System.EventHandler(this.timer1_Tick);

Let's say the timer value is 1 second. On the first run, n-bytes of memory were allocated, on the second run, n-bytes of memory were also allocated, but our program forgets about the first n-bytes of the allocated memory, and the memory leaks.
How to make sure that there is no such memory leak?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Kerman, 2014-02-19
@The_Chemis

A memory leak can indeed occur if this line is run every second. The line adds a handler to the event and should only be fired once, at initialization.
Perhaps there is no leak, you just did not wait for the garbage collector to work. I advise you to set a timer for 10ms and watch the dynamics of memory consumption. The fact is that you really need to allocate some memory for each timer operation, but it is irrational to collect garbage after each operation.

E
Eugene, 2014-02-19
@r4tz52

What happens inside timer1_Tick()?

R
RPG, 2014-02-19
@RPG

Even in a language with a garbage collector, you can "leak" memory. But formally, this is not a leak - sooner or later the garbage collector will clear all memory, the only negative effect is the loss of performance due to frequent calls to the garbage collector.
Getting rid of this effect is simple: you need to rewrite the code so that the operation of creating a new object occurs somewhere outside the loop. This is not always possible, then you just need to reduce the frequency of creating objects in order to increase their lifetime (1 object per second is not so scary). Theoretically, you can still use the reuse of the object. This is abstract advice and applies to any language with a garbage collector.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question