How to dispose of a Forms.Timer on the Compact Framework

958 views Asked by At

On the Compact Framework, the System.Windows.Forms.Timer class doesn't support the system.componentmodel constructor:

new Timer() is supported: http://msdn.microsoft.com/en-us/library/aa335543(v=vs.71).aspx

new Timer(IContainer container) is not supported: http://msdn.microsoft.com/en-us/library/aa335544(v=vs.71).aspx

This means that, when I add a Timer to a Form in a CF app, it does not get added to the form's IContainer components field, so it doesn't get auto-dispose()d when the form is dispose()d.

Why is this not supported?

How should I best dispose of Timers when my form is disposed? It seems that I have two main options:

  • move the form's dispose() method from the .designer.cs into my main .cs file and add a manual "_timer.dispose()" call in there
  • or manually add the Timer object to the components collection on form creation, after InitializeComponent() has been called

Which should I prefer? If I forget to do one of these two, the Timer will live forever, keeping my form alive (because the Timer can't be GCed, and it holds a reference to my form's Timer_Tick() method, so the form can never be GCed).

Does this implementation decision reflect some strangeness about Timers and Disposing on CF machines which I need to be aware of?

1

There are 1 answers

2
ctacke On

I'd vote for option 3: don't add the Timer through the Form Designer; instead add it manually in code and add it to the components collection manually as well.

My reasoning for this follows like this:

  • Mucking with the designer code is just generally a bad idea, so your first option has a code smell to it
  • Adding it to the components collection manually is highly prone to future developers (even yourself in a few months) no understanding why it's there and getting axed.
  • I generally don't like "mixing" object initialization. If the disigner is doing initialization of an object, it needs to do all of it or none of it, never just part. Having it do some partial work is deadly when the code is maintained or during reuse when someone does a copy & paste into some other class.