Why use Windows.Forms.Timer at all? - c#

I read this excellent article Comparing the Timer Classes in the .NET Framework Class Library and came to the conclusion that anything I could do with Windows.Forms.Timer I can do better with Timers.Timer - and then some.
So the obvious question that comes to mind is: Why is the Windows.Forms Timer offered at all?
Legacy (backward compatibility) support?
Other?

The main convenience of the Windows.Forms.Timer is that its events are fired on the UI (Winforms) thread. If your timer events perform UI operations, it may be the simplest alternative (instead of calling Control.Invoke/BeginInvoke or SynchronizationContext.Post/Send inside all of your events).

The Windows.Forms.Timer events get invoked on the UI thread so you can update the UI from the event handlers directly, which is not normally the case with Timers.Timer (as you would get cross thread access violation exceptions).
And, as #Robert Harvey answered, it also has designer support.

One of advantage of Windows.Forms is that it run in the same thread of GUI and you do not get cross thread exceptions while accessing Form controls.

Windows.Forms.Timer has designer support. So it behaves like any other Winforms component (i.e. you can drag it onto a form, it's part of the Controls collection, etc).
Timer events raised by System.Windows.Forms.Timer class are synchronous with respect to the rest of the code in your Windows Forms app. This means that application code that is executing will never be preempted by an instance of this timer class (assuming you don't call Application.DoEvents). Events fired by the Windows.Forms.Timer class are compatible with your Winform controls; you can safely interact with them without having to call Invoke().
The System.Timers.Timer class is a server-based timer that was designed and optimized for use in multithreaded environments. Instances of this timer class can be safely accessed from multiple threads. Although Invoke() is technically required to interact with Winforms, the Timer class does provide a SynchronizingObject property, to which you can attach the Windows form with which you want to safely interact.
More here:
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

Well I think the answer is that they are two completely different types of timers. The Windows.Forms.Timer is a single-threaded application timer that's well suited for timers existing on the client running application.
A Timer is used to raise an event at user-defined intervals. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.
In contrast the Timers.Timer is a server-based timer that is better suited for Windows services.
The Timer component is a server-based timer, which allows you to specify a recurring interval at which the Elapsed event is raised in your application. You can then handle this event to provide regular processing. For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. You could create a service that uses a Timer to periodically check the server and ensure that the system is up and running. If the system is not responding, the service could attempt to restart the server or notify an administrator.
You can find their documentation and read the excerpts and more from Microsoft.
It's not that one should never be used or always used, the serve two different purposes.

My belief is that it is for winform designer integration, in that you can drag it onto a form, click it and set its properties in the properties pane.

Related

Alternative to Timer

I'm developing a c# winform application which is based on third party web API's for trading purpose. It deals with real time data coming from internet like currency rates but I'm using 8 timer in my winform to retrieve different data, application gets non-responding because of timers,
what can i do to make this application work fast and smooth?
You might want to look into the System.Threading.Timer instead:
Timer Class
System.Threading.Timer, which executes a single callback method on a
thread pool thread at regular intervals. The callback method is
defined when the timer is instantiated and cannot be changed. Like the
System.Timers.Timer class, this class is intended for use as a
server-based or service component in a multithreaded environment; it
has no user interface and is not visible at runtime.
This link has a nice table of comparison between the different timer classes at the bottom:
Comparing the Timer Classes in the .NET Framework Class Library
Use threading. Timers (at least the ones you seem to be using) are executed in the GUI's thread. Use BackgroundWorkers (or other threading methods) instead to decouple background tasks from the GUI.

Proper way of executing method in regular interval

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.
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.
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

Porting SetTimer() and KillTimer() to C#?

I am trying to port some code from C++ to C#.
I came across this in the C++ code:
watchdogTimer = SetTimer(1,1000,NULL);
...
KillTimer(watchdogTimer);
What is this code doing, and how can this be ported to C#?
Thanks.
The CWnd::SetTimer function you're looking at creates a timer that sends WM_TIMER events to the window. This is analogous to the System.Windows.Forms.Timer component in .NET. It behaves somewhat differently than the System.Timers.Timer. There are two differences that are particularly relevant:
Windows.Forms.Timer calls the event handler on the UI thread. By default, System.Timers.Timer calls the event handler on a threadpool thread. You can use SynchronizingObject property to have the System.Timers.Timer call on the UI thread.
Another difference is that it's not possible to encounter reentrancy problems with the Windows Forms timer because Windows won't allow multiple WM_TIMER messages from the same timer in the queue, nor will it place a WM_TIMER message in the queue if one is already being processed. This is generally a good thing.
System.Timers.Timer, on the other hand, will allow reentrancy. So if your timer event handler takes longer than the timer period, you can be processing multiple events for the same timer concurrently. If your timer period is 100 ms and processing takes 150 ms, you're going to get another notification while you're processing the first one. If you use the SynchronizingObject to force the callback on the UI thread, this can lead to a whole bunch of pending callbacks being queued.
The implementation of the two timers is quite different. The Windows Forms timer uses old style Windows timers that have been around for 20 years. This type of timer requires a window handle and a message loop, and is therefore used only in GUI programs. System.Timers.Timer is a thin wrapper around System.Threading.Timer, which uses the Windows Thread Pool Timers.
Assuming that your application is written under MFC, the SetTimer() method belongs to class CWnd and is responsible for setting up a windows timer. Documentation for this can be found at http://msdn.microsoft.com/en-us/library/49313fdf(v=vs.80).aspx. I know little about .NET but a quick google search located the following this: http://msdn.microsoft.com/en-us/library/0tcs6ww8(v=VS.90).aspx.

Timers and multithreading

I have a question about timers and threads. I noticed that the timers misbehaving when started within the threads, while the timers are part of the Winform.
Generally I'm interested in problems related threads and timers.
Happy New Year to you all, the answers may be to wait until 2011:)
Sounds like you're using a System.Threading.Timer and using a TimerCallback that performs GUI updates. Is that it?
There are a number of correct ways to deal with this. Use a System.Windows.Forms.Timer and handle its Tick event if you're looking to update the UI. Use a BackgroundWorker, do non-UI work in its DoWork event and then perform UI updates in its RunWorkerCompleted event if you're performing long-running background tasks.
In general, the important thing to understand about multithreading as it pertains to Windows Forms is this: all Windows Forms application have a UI thread, which is the only thread that is allowed to perform UI updates. It is continually processing a queue onto which user actions are pushed and handle via events. When you try to do anything that updates a UI control from any thread besides this thread, you get an exception because this behavior was not planned for in the design of Windows Forms components, and would therefore very likely cause bugs or possibly crash the entire application.
So the approach to multithreading is generally to separate work into two parts, that which can be done in the background (on a non-UI thread) and that which must sent to the queue being processed by the UI thread so that it can be handled in a safe manner. The usefulness of types like System.Windows.Forms.Timer and BackgroundWorker is that they encapsulate many of the difficult details of this process for you, allowing you to focus on the code you want to run.
That's a high level view of how multithreading works with Windows Forms. I'm sure others can provide plenty of references pointing you to more information on the subject (and if nobody else does, maybe I can look some up later).
Comparing the Timer Classes in the .NET Framework Class Library is a good article to read.
Google maybe?
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

How to program asynchronous Windows Forms Applications?

I'm writting a Windows Forms application in C# that performs a lot of long-running procedures. I need to program the application so that the GUI doesn't lock. What is the best way to program it?
I know how to use the following:
BeginInvoke/EndInvoke
Calling Application.DoEvents() repeatedly (probably not a good idea)
BackgroundWorker
etc.
But how to manage GUI state with call backs, etc... is not trivial. Are there solutions for this (in the form of patterns or libraries)?
Using BackgroundWorker is the simplest way to do what you're trying to do. BackgroundWorker simplifies the logic of dealing with threads, leaving you with very little code you have to write. You just have to handle three events (DoWork, ProgressChanged, and RunWorkerCompleted) and follow a few principles:
Don't ever update the UI inside your long-running method. Have it call ReportProgress instead and handle the ProgressChanged event in the UI logic.
Understand that since the worker isn't running on the UI thread, an exception that your method throws doesn't automatically show up in the UI. It just gets silently written to the console. It's very important to check the Error property of the RunWorkerCompletedEventArgs when the method is done and handle (or throw) the exception. If you don't do this, you won't know that your method failed.
If the method can be cancelled, make sure that it periodically checks the CancellationPending property to see if cancellation has been requested. If it has, once it's done handling the cancellation, set the Cancel property on the DoWorkEventArgs object. Be aware that it's possible for CancellationPending to be true and Cancel to be false; this happens, for instance, when the user requests cancellation and the method finishes before it has a chance to check CancellationPending.
Correspondingly, check Cancel in your RunWorkerCompleted event handler, so that your UI can provide the proper response to what happened while the worker was running.
The examples in the documentation all show the DoWork event handler calling a method of the form. This is almost certainly not what you want to do. Separating business logic from UI is a good idea in general; in background tasks it's essential. If your long-running method is a member of a class that doesn't know that the UI even exists, there's no danger that you'll inadvertently have it call a method that updates a status bar or something.
The Model-View-Controller pattern separates the state of your UI from the visual aspects of the UI. As long as your MVC implementation is thread aware, it should solve the state management issue for you.
This is how I handle multi-threaded UI implementations.
EDIT: Here's a good post on selecting an MVC implementation for WinForms projects.
It is relatively simple to use the ThreadPool to fire off long running processes from the UI. If you want feedback you can use some event handlers to fire on certain events from the long running process, then register for them and update the UI as needed.
MVC is good, but you still need to make sure your process is firing off on a thread other than the UI thread.
All your options are syntactic sugar of doing same thing (Asynchronous execution). May be with different levels of controls. I would go with BackgroundWorker, because your GUI (handled by the main thread) will always be responsive.

Categories