Reputation: 11468
I want to execute the certain method of a class in regular interval when certain method is executed. C# has three methods I can use to furnish my needs. Since I am new to C# programming, I am confused in selecting the right method. Based on my study, the three classes are:
System.Windows.Forms.Timer
Systems.Timer
System.Diagnostics.StopWatch
My requirement is fairly simple: Execute the certain method at regular interval when the certain method is called.
Please suggest the situation where one is more preferred over others.
Upvotes: 0
Views: 823
Reputation: 164281
StopWatch
is for measuring time, not for scheduling events, so let's rule that one out.
System.Windows.Forms.Timer
is based on Windows Forms and requires the Windows message loop to run. Is your project Windows Forms, then you can use this. If not, do not use it (it won't work).
System.Timers.Timer
is a general purpose timer. I would use this; it should work in all scenarios, you don't have to worry about the message loop running. You can also make this Timer synchronize automatically using it's SynchronizationObject
property.
Finally, there is a System.Threading.Timer
, which is not thread safe out of the box (meaning your method will get called on a worker thread, so if you need synchronization or dispatch on a specific thread due to UI, you will need to handle that yourself).
There are many subtle differences to these timers, I'd recommend you read the article Comparing the Timer Classes on MSDN for the full story.
Upvotes: 2
Reputation: 9858
Without knowing your specific use case, we can't tell you which is best. But in general:
System.Windows.Forms.Timer
- Will call your function on the UI thread each time. Use this if you are planning to access UI controls during the event.
System.Timers.Timer
- Will call your function on a worker thread. Use this in a context that is not Windows Forms or where you don't need to access any UI elements
System.Diagnostics.StopWatch
- this is for timing how long things take. It won't help you here.
See: http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
Upvotes: 1