-4

Please let me know if the following design is bad for managing heap /memory and from a design pattern point of view also. Here I am using a C# Timers.Timer on a windows service where the time tick event fires on multiple threads.

Here my main point is about heap memory consumption , since lots of objects being created in different threads in micro sec and also we cannot guarantee when GC will collect them. so this can be harmful to heap and performance issue later to the application.Am i correct.

timer_tick()
{
 Test objTst=null;
     try
  {
    objTst=new Test();
    objTst.Process();
  }
  catch(execption e){}

  finally
  {
    objTst =null;
  }

}
trincot
  • 317,000
  • 35
  • 244
  • 286
  • 3
    This is a duplicate, but I can't find the dupe now. No, you don't need to set things to `null`. – John Saunders May 02 '14 at 18:15
  • possible duplicate of [Setting Objects to Null/Nothing after use in .NET](http://stackoverflow.com/questions/2785/setting-objects-to-null-nothing-after-use-in-net) – gregwhitaker May 02 '14 at 18:20
  • While this is partly a duplicate of that, there's more to it (in terms of bad practice) than just setting to null unnecessarily... – Reed Copsey May 02 '14 at 18:21

1 Answers1

3

Please let me know following design is bad for manage heap /memory wise and design pattern wise also.

This "pattern" serves no purpose. Setting the variable to null is not required. As soon as the method completes, and objTst goes out of scope, it will be eligible for garbage collection, even if you don't set it to null.

I would also recommend not having an empty exception handler that just swallows and ignores exceptions entirely. If nothing else, you should at least log the exception you receive.

In general, I would write this as:

private void timer_Tick(object sender, EventArgs e)
{
     var tester = new Test();
     tester.Process();
}

If you have an exception logging mechanism, you could wrap it in a try/catch to handle or log the exceptions, but don't just swallow them completely.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Here my main point is about heap memory consumption , since lots of objects being created in different threads in micro sec and also we cannot guarantee when GC will collect them. so this can be harmful to heap and performance issue later to the application.Am i correct. – user3597242 May 02 '14 at 19:55
  • @user3597242 It should be fine - the GC will collect as needed. Setting to `null` won't change that behavior at all, though – Reed Copsey May 02 '14 at 20:06
  • Thanks.Is there any Microsoft tool that we can check heap memory management of particular application – user3597242 May 02 '14 at 20:15
  • @user3597242 Higher end versions of Visual Studio include memory profiling tools – Reed Copsey May 02 '14 at 20:19