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.
Related
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.
Here's what I have. When my application starts up, it creates a thread and runs my startListening() function. But what it seems to do, is run any other functions called within startListening under the same thread. Is there a way I can make it so that ONLY the things immediately inside of startListening are ran with that thread, and not the functions called from within that?
It would just make it a lot easier for me when referencing controls and things that aren't within that thread so I don't have to Invoke each time.
EDIT: Maybe this isn't the right thing to be asking. I know I had to Invoke with setting textboxes, but now I need to make a timer enabled. Its not throwing any exceptions when I try to enable it, but rather just not "ticking". Here's my code:
private void beginListenerThread()
{
Thread thread1 = new Thread(startListening);
thread1.Start();
}
private void startListening()
{
timer1.enabled = true;
}
But it doesn't tick.
Thanks!
No, that's not possible automatically. If you are able to modify the method that should be called on another thread, change the calls to other methods so that they're run on the originating thread. If you're using Windows Forms, use this.Invoke or this.BeginInvoke, for example.
Yes, this is the kind of trouble you'll run into when you use a class that is not thread-safe on a thread. The Winforms Timer class generates Tick events from a little hidden helper window, a window that receives WM_TIMER messages generated by the Windows SetTimer() api function and turns them into Tick event calls. That window is created when you enable the timer.
What goes wrong here is that this window gets created on the wrong thread. It needs a message pump to dispatch the WM_TIMER notifications, that thread doesn't have one. It could have one by calling Application.Run() but you don't want to go there.
Follow the advice given in the MSDN Library article's Remarks section:
The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.
Or the System.Threading.Timer class, a timer class that's a bit less cranky.
I have a main thread that creates a form object which creates and sets a timer to run a function named updateStatus() every minute. But updateStatus() is also called by the main thread at several places.
However, I am not clear about whether or not it will cause any synchronization problems. Does the System.Windows.Forms.Timer in C# run on a different thread other than the main thread?
No, the timer events are raised on the UI thread.
You won't have any synchronicity problems. This is the correct version of the timer control to use in a WinForms application; it's specifically designed to do what you're asking. It's implemented under the hood using a standard Windows timer.
The documentation confirms this in the Remarks section:
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.
When you use this timer, use the Tick event to perform a polling operation or to display a splash screen for a specified period of time. Whenever the Enabled property is set to true and the Interval property is greater than zero, the Tick event is raised at intervals based on the Interval property setting.
No, the timer's Tick event is raised from the UI thread by the message loop when it receives a WM_TIMER message. You're always good with that, it can only run when your UI thread is idle.
No.
The whole point of a Windows.Forms Timer is that it runs on the GUI Thread.
Windows (WinForms) runs something called the MessagePump (see Application.Run()) and this is what makes the Timer possible.
All your code runs as part of an Eventhandler somehow, and a Timer tick will never 'interrupt' any other event handler.
The Windows.Forms timer raises the event back on the UI thread, presumably via the sync-context.
If you want a non-UI thread, there are other timers - for example System.Timers.Timer or System.Threading.Timer
According to the documentation it runs on the main UI thread:
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.
I don't want to impeach the reputation of others how has answered, that Windows.Forms.Timer does always run on GUI thread, but I have to contradict. :)
I would answer - it depends. It can be, that Windows.Forms.Timer does run on Non-GUI thread!
Windows.Forms.Timer does fire it's Timer.Tick event on the thread, where the Form, which contains the timer, has been created.
If the form is created on the GUI thread, then the Timer.Tick runs on GUI thread, if however Form is created on the e.g. some thread XXX from thread pool(what you should avoid), then the Timer.Tick runs on this XXX thread.
Task.Run(()=>
{
using (var formWithTimer = new SomeFormWithTimer()) //Form created on worker thread, Tick handled on it.
{
formWithTimer.ShowDialog();
}
});
How much overhead do timers cause in an application if they are running in the background continuously (regardless of the interval)?
I'm not worried about the calls that the timer will make when it ticks, but rather about the performance effects of using timers in applications where performance is of the utmost importance and am interested to hear what views there are on this.
The timer, between it's ticks, adds an extremely low cost to the application. It uses the OS's mechanism for schedualing (which is active regardless of your actions), as opposed to the intuitive concept of polling the system's clock constently.
Basicly, other then the added memory and context switch data addition (minor additions in this case. Shouldn't be more then adding a button to your form) there shouldn't be any more overhead.
The event invoked by the Timer will run in the same thread that the timer belongs to, and therefore will block that thread while performing any logic. That means that if the Timer belongs to the GUI layer, the execution of the Timer.Tick method will lock up the GUI while it's running.
To maintain performance in the main thread, i suggest using a BackgroundWorker instead that runs in it's own thread.
To answer in a same way: timers are invaluable for gui programming, but are pretty much useless for high performance tasks. Some issues with timers:
they aren't regular to the millisecond (in fact in windows, nothing is) - it will fire when is its time, but when all other messages (mouse-keyboard events, control updates) are processed, because it is serialized with other messages from/to gui
don't know .net implementation, but they wasted handles in mfc
If you are considering another thread for some operation, make sure that you don't touch any gui component from it. Use either Invoke() or copy updates for a gui to some queue, then dequeue it with timer from gui main thread.
I have a problem with interface lag in C#.
Since I'm still learning please be patient whilst I explain.
I have narrowed the problem to my timer object.
Basically my program queries a device through TCP/IP socket and outputs it to a textbox on screen.
Now I am polling the device for data every second which requires some logic to be buried within timer object and the following is what happens between ticks:
Increment a value.
Construct the 2 strings that represents the command to be sent to
the box (encapsulated in a function
Encode the command
Send command
Clear the byte array
Receive reply.
Could this be too much processing being done in the event handler? Every time I try to move the window during the polling session i.e. when the timer is running I get a very bad input lag.
The timer you are using is executing on the windows message thread. Therefore, while the polling is running the windows message queue is blocked. This isn't a problem with doing too much processing, most of the time the thread will be waiting for the TCP/IP response.
To fix this, you just have to do the do the work on a background thread and then update the UI on the UI thread.
There are a heap of different timers in the .NET framework that work in different ways, the one you are using works processed the timer event on the same thread, others work on background threads. Check this article out about the different timers.
You could also just use your current timer to invoke a BackgroundWorker component to do the work on the background thread. The main benefit of this is the the BackgroundWorker will do the work on a background thread, but will raise the work complete event on the UI thread so that it is simple to update the UI without having to worry about which thread you are on.
I think this is because you're trying to do work in your UI thread. Have your timer run in a background work thread.
It seems like there are a few things going on. First, you may be doing too much in your timer tick handler. How are you constructing the string and encoding the command? Can any of this be done once outside the tick handler or simplified in any way (using String.Format calls, for instance)? There are actually three different timers available in .NET, with different resolutions. Which timer are you using?
The biggest issue is the fact that your interval is 1 second. No matter what, that is a lot of processing overhead. Keep in mind that, for the most part, every time the interval is hit and the tick handler is invoked you are causing a context switch between threads. There is a bit of overhead involved in this (nothing which you can do anything about) and the more often you context switch the slower your performance appears.