tags:

views:

660

answers:

4

C# What is the easiest way to disable a control after 10 seconds? Using a Timer or a stopwatch? I'm new to both so thanks for the help.

A: 

Use a timer. It suits your needs better.

EDIT: As other have said, go with the System.Windows.Forms.Timer

Galwegian
Ah, but which one? There are 3 different timers in the bcl.
Joel Coehoorn
+11  A: 

I'm not sure how you'd expect stopwatch to help. A timer certainly sounds like the right answer to me. You should be aware that there are several different timers available - in this case System.Windows.Forms.Timer is probably the one you want for a WinForms app, or a System.Windows.Threading.DispatcherTimer for WPF.

Jon Skeet
Unless he's doing WPF. It's a bit of overkill to bring the WinForms for the timer only... :-)
Franci Penov
True. I had been assuming System.Windows.Forms. Editing...
Jon Skeet
obviously "while(stopwatch.ElapsedTime < x);" is the way to go ;)
Jimmy
+4  A: 

Windows forms has a Timer control (here's WPF's version).

The reason why you use these is because these timers fire on the UI thread, so you don't have to do the usual multithreaded if-InvokeRequried-Invoke dance that you would have to do if you used System.Threading.Timer or some other method that ran on a different thread.

(stole the WPF link from Jon)

Will
Dead on. There's also System.Timers.Timer and System.Threading.Timer, but since this is for a UI element the Forms timer is probably the way to go.
Joel Coehoorn
Yep, no need for InvokeRequired with the form's Timer.
Will
+3  A: 

Related to @Jon Skeet's answer, the reason you want the System.Windows.Forms.Timer timer (out of the 3 in the framework) is that it will take care of executing your timer code on the UI thread for you. The other timers don't do that for you so you're left to calling .CanInvoke and Invoke() all over (or using a SynchronizationContext which is a bit simpler, but still cumbersome).

Jeremy Wiebe
You can specify the target thread for the System.Timers.Timer, but it's extra work you don't need with the Forms timer.
Joel Coehoorn
Well, I didn't know that! Thanks Joel.
Jeremy Wiebe