If have an object that looks like this:
public class MyTask
{
private Connection _someKindOfConnectionThatShouldStayOpen;
public MyTask() { ... Opens connection and other stuff }
void DoWork(object arg) { ... }
}
I want to create a small application that creates the object and run the DoWork method periodically (say every second), without destroying the object.
What is the best way of doing this? (ie. safest and best practice)
You can certainly use a Timer. The timer’s callback can call DoWork.
Have the Timer be a private field of your object. Instantiate and start it when the object is instantiated.
Implement IDisposable for your object and be sure you dispose the timer when you dispose of your object.