Search code examples
c#objectgarbage-collectiondispose

Disposing of an Object that is used repeatedly


I have looked around, and I cannot find what is the best practice for this. I have a loop that creates an object and then disposes of it each time a process is run. However, this object is always the same and is used in the program every minute or so, which is also how often the other processes in the program run. Should I call Dispose(); on this object every time the process is run or just keep it since it is always exactly the same? The language is C#.


Solution

  • If it works the way you've written it, seems like you shouldn't change it. Unless the object is particularly expensive to create or destroy. But if you don't need the object except during that brief period every minute, why keep it around?

    Look at it this way. If the object is only used by that one particular task, then having that task control the object's lifetime makes for simpler code. Otherwise your main program will have to create the object at startup and dispose of it at shutdown. Also, other threads or tasks within the program then potentially have access to it. Restricting access to just the task that needs it can prevent a whole host of other problems.