Reputation: 855
In my application UI, I am updating one of grid through Windows Timer tick every 1 sec.
It's not working properly when I am doing some other UI operations belongs to another windows forms(this is basically using tabbed forms)
I added trace for Timer_Tick event and logged in to file.
We found there is an missing of log data, when another UI operation going on (Open and closing of another windows form). Timer_Tick not hitting at this time.
Any suggestions...?
Upvotes: 3
Views: 4309
Reputation: 134005
The System.Windows.Forms.Timer
tick event executes on the UI thread. If the UI thread is busy doing something else, then the timer tick handler will have to wait.
The tick events for System.Threading.Timer and System.Timers.Timer happen on threadpool threads, so they can execute while the UI thread is busy. If you need to update the UI from your tick handler, you can call BeginInvoke, and the UI update will happen when the UI thread is free.
There's no need to start a different thread or a BackgroundWorker
that executes a Sleep
loop.
Upvotes: 4
Reputation: 16564
The issue is that the UI is running in a single thread. Any long-running blocking operation on that thread - like opening a form, running some code in response to a button click, etc - will prevent the timer from firing. This is the nature of single-threaded programming.
If you absolutely need to run code every second, regardless of what is happening in the UI thread, you'll need to use a second thread.
Related Links:
System.Threading.Thread
documentationSystem.Threading.Tasks.Task
documentationSystem.Threading.Timer
documentationAnd very important, for interacting with your UI from any of the above:
System.Windows.Forms.Control.Invoke
method documentationSystem.Windows.Forms.Control.InvokeRequired
property documentationUpvotes: 5
Reputation: 1967
You can run it on a BackgroundWorker since it just happens every 2 seconds without user interaction. For more details about BackgroundWorker, check this article "http://www.dotnetperls.com/backgroundworker" it's very easy to understand.
BackgroundWorker makes threads easy to implement in Windows Forms. Intensive tasks need to be done on another thread so the UI does not freeze. It is necessary to post messages and update the user interface when the task is done.
Upvotes: -1