The documentation of System.Threading.Timer says that I should keep a live reference for it to avoid it being garbage collected. But where should I do that? My main is very simple that I don’t know where to keep the reference:
class Program { static void Main() { new System.Threading.Thread(myThreadStart).Start(); new System.Threading.Timer(myTimerCallback, new MyStateObject(), 0, 5000); } }
I thought about keeping the reference in a static field in the Program class, assuming that static fields do not get collected until the end of the application. But I’m not sure this is the best way to do it, so I’d appreciate your advice.
If your Timer is an application-level object there’s nothing wrong with making it a private static member of your Main class. That’s what I would do, anyway.