Answer the question
In order to leave comments, you need to log in
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);
Answer the question
In order to leave comments, you need to log in
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.
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 questionAsk a Question
731 491 924 answers to any question