Reputation: 2271
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#.
Upvotes: 0
Views: 154
Reputation: 135
Maybe you should be looking at the using statement. It disposes the object after use. See this
this is the syntax
using (var myObject = new MyCustomObject())
{
//Do something with my object
}
Upvotes: 0
Reputation: 1238
Create the object only once and call dispose on closing youre app. It also depends a little on what you're doing.
Upvotes: 0
Reputation: 1396
You should keep it somewhere if it takes a long time to initialize.
Depending on what the object is, you might also want to consider making it a singleton. Singletons are particularly useful when you have an object that takes a long time to initialize, and/or if the object is used in multiple places.
Upvotes: 0
Reputation: 134125
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.
Upvotes: 5