Home > .Net, C# > Working with System.Timers.Timer causing memory leaks

Working with System.Timers.Timer causing memory leaks

Short preamble,

Recently we had very serious problem with our application written in C#.NET; sometimes it has been completely stuck. This wasn’t easy reproducible scenario. As we started investigate the issue and debugging, more and more interesting things came up (not all code was written by our team, so debugging was not very easy thing). Memory almost wasn’t affected, but there was another symptom: thread count was growing and growing.

Finally the problem was discovered as following:

Our Client computers, where the application running, have established .Net Remoting communication with other distributed part of our system (yes, this code was developed long before WCF came in to the picture with all cool features like discovery etc., may be one day we will rewrite it). We have used server-based Timer component (which gives more accuracy than Windows timers in raising the event on time), to check connection state and reconnect if needed.

Autoreset property of the Timer class by default set to true, which means that it will keep raising after every time interval.

See following code with Lock synchronization:
Callback method …

MyTimer.Elapsed += new ElapsedEventHandler(OnTimerElapsed);

private void OnTimerElapsed()
                //Open remote connection

                //Do some actions

Every time Interval will be opened new thread and stuck in the Lock statement because by default Remoting timeout was higher than Timer Elapsed interval – as a result thread count was growing till the process is stucked. This small functionality caused us lots of problems.

The solution was to play with remoting time out and on the other hand set Autoreset to false and restart timer only after reconnecting to the server.

We should be very careful when you using system timers namespace.

Categories: .Net, C# Tags: , , ,
  1. Vlad
    April 22nd, 2011 at 00:09 | #1

    Use Threading.Timer instead.

  2. ICriteria
    April 22nd, 2011 at 08:43 | #2

    There is no golden rule when to use which kind of timer:
    Each specific system design need to decide what Timer class to choose (there are at least three different timers in .Net). In this post i just described interesting problem that our team has solved.
    timer from Threading namespace more complicated to use and still not thread safe.

    for more detailed explanations you can read related article http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

  1. No trackbacks yet.