473,725 Members | 1,956 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

System.Timers.T imer and InvokeRequired

Hi all,

I set up a System.Timers.T ime in my app. The code basically just updates
the screen, but since the processing performed is so CPU-intensive, I wanted
to make sure it gets updated regularly; like every 1.5 secs. or so. I only
ran into one issue - the MyTimer_Elapsed event handler was not updating the
screen correctly all the time, often leaving large chunks of the screen
un-painted for several seconds.

On a whim I decided to check the InvokeRequired property of my form in the
Event Handler... and whaddyaknow, it was True. So now I've added the proper
code to check InvokeRequired and to update the screen using Invoke(), but I
hadn't realized I needed to use Invoke to update the screen from within the
System.Timers.T imer? Even in the sample MSDN code for the
System.Timers.T imer they leave out the Invoke(); i.e.:

Private Sub myTimer_Elapsed (ByVal sender As System.Object, ByVal e As
System.Timers.E lapsedEventArgs )
System.Windows. Forms.MessageBo x.Show("Elapsed !", _
"Timer Event Raised!")
End Sub

While I know that Invoke() must be called to update the UI from worker
threads, outside of that is its usage more or less a matter of trial and
error? Or are there additional rules that should be followed when
determining when to use Invoke()?

Just wondering. Thanks.
Nov 21 '05 #1
5 9886
The System.Timers.T imer runs on a different thread to the main UI of the
application. Even though the code for the timer service might be in your
form, the thread it's called on will be different and therefore you'll need
to check to see if other methods in your form or class should be called
using invoke.

Generally, you should know whether you're using threads either explicitly or
implicitly as in the case of System.Timers.T imer and code for those
circumstances. Unfortunately the only way to know this is to read the fine
print in the docs.

Don't cite MSDN as a shining example. It's full to bursting with
horribleness. See if you can find an example of Dispose being used on a
Graphic object in there...

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Michael C#" <xy*@yomomma.co m> wrote in message
news:eY******** ******@TK2MSFTN GP15.phx.gbl...
Hi all,

I set up a System.Timers.T ime in my app. The code basically just updates
the screen, but since the processing performed is so CPU-intensive, I
wanted to make sure it gets updated regularly; like every 1.5 secs. or so.
I only ran into one issue - the MyTimer_Elapsed event handler was not
updating the screen correctly all the time, often leaving large chunks of
the screen un-painted for several seconds.

On a whim I decided to check the InvokeRequired property of my form in the
Event Handler... and whaddyaknow, it was True. So now I've added the
proper code to check InvokeRequired and to update the screen using
Invoke(), but I hadn't realized I needed to use Invoke to update the
screen from within the System.Timers.T imer? Even in the sample MSDN code
for the System.Timers.T imer they leave out the Invoke(); i.e.:

Private Sub myTimer_Elapsed (ByVal sender As System.Object, ByVal e As
System.Timers.E lapsedEventArgs )
System.Windows. Forms.MessageBo x.Show("Elapsed !", _
"Timer Event Raised!")
End Sub

While I know that Invoke() must be called to update the UI from worker
threads, outside of that is its usage more or less a matter of trial and
error? Or are there additional rules that should be followed when
determining when to use Invoke()?

Just wondering. Thanks.

Nov 21 '05 #2
In article <eY************ **@TK2MSFTNGP15 .phx.gbl>, Michael C# wrote:
Hi all,

I set up a System.Timers.T ime in my app. The code basically just updates
the screen, but since the processing performed is so CPU-intensive, I wanted
to make sure it gets updated regularly; like every 1.5 secs. or so. I only
ran into one issue - the MyTimer_Elapsed event handler was not updating the
screen correctly all the time, often leaving large chunks of the screen
un-painted for several seconds.

On a whim I decided to check the InvokeRequired property of my form in the
Event Handler... and whaddyaknow, it was True. So now I've added the proper
code to check InvokeRequired and to update the screen using Invoke(), but I
hadn't realized I needed to use Invoke to update the screen from within the
System.Timers.T imer? Even in the sample MSDN code for the
System.Timers.T imer they leave out the Invoke(); i.e.:

Private Sub myTimer_Elapsed (ByVal sender As System.Object, ByVal e As
System.Timers.E lapsedEventArgs )
System.Windows. Forms.MessageBo x.Show("Elapsed !", _
"Timer Event Raised!")
End Sub

While I know that Invoke() must be called to update the UI from worker
threads, outside of that is its usage more or less a matter of trial and
error? Or are there additional rules that should be followed when
determining when to use Invoke()?

Just wondering. Thanks.


The rule is that if the procedure that is updating your UI is on another
thread, you must use invoke to marshal back to that thread. This is
necessary with System.Timers because all the calls happen on a
ThreadPool thread.

That said, the System.Timer.Ti mer component has the ability to
automatically marshal calls to a specific object via the SyncronizingObj ect
property. If you add the component from the components dialog in the
ide to a form, it should automatically set this to the form. If you
creat the object in code - then this will be null (nothing in vb) and
you have the problem you mentioned. So, if you create it in code, you
could always set it to the form you want to update it manully - before
you start it ticking :)

--
Tom Shelton [MVP]
Nov 21 '05 #3
Thanks for the info. While we're on the topic, is it ok to assume that
Invoke needs to be called for *all* UI objects at a given point in time if
InvokeRequired is True for the Form itself? In a lot of code I've seen, for
some reason the authors feel the need to check InvokeRequired for each and
every object they're updating on the UI; every text box, each label, all
progress bars, etc. It seems that if the form itself needs to be Invoked,
then all of the controls it contains would need to be Invoked. Is this a
safe assumption? Or is there a special reason to call InvokeRequired
multiple times for each individual control?

Thanks again

"Bob Powell [MVP]" <bob@_spamkille r_bobpowell.net > wrote in message
news:ea******** ******@TK2MSFTN GP10.phx.gbl...
The System.Timers.T imer runs on a different thread to the main UI of the
application. Even though the code for the timer service might be in your
form, the thread it's called on will be different and therefore you'll
need to check to see if other methods in your form or class should be
called using invoke.

Generally, you should know whether you're using threads either explicitly
or implicitly as in the case of System.Timers.T imer and code for those
circumstances. Unfortunately the only way to know this is to read the fine
print in the docs.

Don't cite MSDN as a shining example. It's full to bursting with
horribleness. See if you can find an example of Dispose being used on a
Graphic object in there...

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Michael C#" <xy*@yomomma.co m> wrote in message
news:eY******** ******@TK2MSFTN GP15.phx.gbl...
Hi all,

I set up a System.Timers.T ime in my app. The code basically just updates
the screen, but since the processing performed is so CPU-intensive, I
wanted to make sure it gets updated regularly; like every 1.5 secs. or
so. I only ran into one issue - the MyTimer_Elapsed event handler was not
updating the screen correctly all the time, often leaving large chunks of
the screen un-painted for several seconds.

On a whim I decided to check the InvokeRequired property of my form in
the Event Handler... and whaddyaknow, it was True. So now I've added the
proper code to check InvokeRequired and to update the screen using
Invoke(), but I hadn't realized I needed to use Invoke to update the
screen from within the System.Timers.T imer? Even in the sample MSDN code
for the System.Timers.T imer they leave out the Invoke(); i.e.:

Private Sub myTimer_Elapsed (ByVal sender As System.Object, ByVal e As
System.Timers.E lapsedEventArgs )
System.Windows. Forms.MessageBo x.Show("Elapsed !", _
"Timer Event Raised!")
End Sub

While I know that Invoke() must be called to update the UI from worker
threads, outside of that is its usage more or less a matter of trial and
error? Or are there additional rules that should be followed when
determining when to use Invoke()?

Just wondering. Thanks.


Nov 21 '05 #4
In article <eR************ **@tk2msftngp13 .phx.gbl>, Michael C# wrote:
Thanks for the info. While we're on the topic, is it ok to assume that
Invoke needs to be called for *all* UI objects at a given point in time if
InvokeRequired is True for the Form itself? In a lot of code I've seen, for
some reason the authors feel the need to check InvokeRequired for each and
every object they're updating on the UI; every text box, each label, all
progress bars, etc. It seems that if the form itself needs to be Invoked,
then all of the controls it contains would need to be Invoked. Is this a
safe assumption? Or is there a special reason to call InvokeRequired
multiple times for each individual control?

Thanks again


I only check the form... I see no need to check all it's child
controls, since they are going to be on the same thread as the form.
So, basically, if the form returns true for InvokeRequired, all it's
contained controls are going to as well.

--
Tom Shelton [MVP]
Nov 21 '05 #5
Most applications will be single threaded and so one can assume that
checking InvokeRequired is not necessary. Threaded UI updates are not
recommended but they are possible but any developer using them needs to be
aware of the problems they can cause and techniques to keep the app running
sweetly.

The rule of thumb is one thread means no need to bother with InvokeRequired
ever. More than one thread means that you ALWAYS check from the non-UI
threads.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Michael C#" <xy*@yomomma.co m> wrote in message
news:eR******** ********@tk2msf tngp13.phx.gbl. ..
Thanks for the info. While we're on the topic, is it ok to assume that
Invoke needs to be called for *all* UI objects at a given point in time if
InvokeRequired is True for the Form itself? In a lot of code I've seen,
for some reason the authors feel the need to check InvokeRequired for each
and every object they're updating on the UI; every text box, each label,
all progress bars, etc. It seems that if the form itself needs to be
Invoked, then all of the controls it contains would need to be Invoked.
Is this a safe assumption? Or is there a special reason to call
InvokeRequired multiple times for each individual control?

Thanks again

"Bob Powell [MVP]" <bob@_spamkille r_bobpowell.net > wrote in message
news:ea******** ******@TK2MSFTN GP10.phx.gbl...
The System.Timers.T imer runs on a different thread to the main UI of the
application. Even though the code for the timer service might be in your
form, the thread it's called on will be different and therefore you'll
need to check to see if other methods in your form or class should be
called using invoke.

Generally, you should know whether you're using threads either explicitly
or implicitly as in the case of System.Timers.T imer and code for those
circumstances. Unfortunately the only way to know this is to read the
fine print in the docs.

Don't cite MSDN as a shining example. It's full to bursting with
horribleness. See if you can find an example of Dispose being used on a
Graphic object in there...

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Michael C#" <xy*@yomomma.co m> wrote in message
news:eY******** ******@TK2MSFTN GP15.phx.gbl...
Hi all,

I set up a System.Timers.T ime in my app. The code basically just
updates the screen, but since the processing performed is so
CPU-intensive, I wanted to make sure it gets updated regularly; like
every 1.5 secs. or so. I only ran into one issue - the MyTimer_Elapsed
event handler was not updating the screen correctly all the time, often
leaving large chunks of the screen un-painted for several seconds.

On a whim I decided to check the InvokeRequired property of my form in
the Event Handler... and whaddyaknow, it was True. So now I've added
the proper code to check InvokeRequired and to update the screen using
Invoke(), but I hadn't realized I needed to use Invoke to update the
screen from within the System.Timers.T imer? Even in the sample MSDN
code for the System.Timers.T imer they leave out the Invoke(); i.e.:

Private Sub myTimer_Elapsed (ByVal sender As System.Object, ByVal e As
System.Timers.E lapsedEventArgs )
System.Windows. Forms.MessageBo x.Show("Elapsed !", _
"Timer Event Raised!")
End Sub

While I know that Invoke() must be called to update the UI from worker
threads, outside of that is its usage more or less a matter of trial and
error? Or are there additional rules that should be followed when
determining when to use Invoke()?

Just wondering. Thanks.



Nov 21 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
16904
by: Peter Johnsson | last post by:
How come the eventhandler for the timer's elapsed time event is called over and over again, even though the AutoReset property is set to false, if you assign a new value to the timer objects interval property inside the event handler? Example follows: Constructor: mTimer = new System.Timers.Timer(20000); mTimer.AutoReset = false;
9
7875
by: Mark Rae | last post by:
Hi, I've seen several articles about using System Timers in ASP.NET solutions, specifically setting them up in Global.asax' Application_OnStart event. I'm thinking about the scenario where I might need to carry out some back-end processing without pausing the individual users' Session while that process runs. E.g. I might provide the ability for a user to upload a text file of job
10
2706
by: WhiteSocksGuy | last post by:
Help! I am new to Visual Basic .Net (version 2002) and I am trying to get a System.Timers.Timer to work for me to display a splash screen for about two seconds and then load the main form. I have two forms (frmSplash and frmMain) and a code Module setup as my startup object. Here is the code that I have, when I try to run this part of the splash screen form shows and then program terminates. What am I doing wrong? Thanks,
1
2115
by: melanieab | last post by:
Hi, I'm have a datagrid, and I'm trying to have a tooltip pop up if a cell has been hovered on for 2 seconds. I was thinking of using DataGrid.Hover, but then decided to try this instead: static System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); private void dg_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { System.Timers.Timer timer = new System.Timers.Timer();
2
2211
by: cntams | last post by:
All, I have a Windows Service and it has one System.Timers.Timer that fires every 500 milliseconds. Now I have noticed that there's a bug in System.Timers.Timer when it's being used combined with Windows Service. That is, the Timer won't fire again once it's stopped (Timer.Stop() or Timer.Enabled = False) (http://support.microsoft.com/kb/842793/en-us). Instead of using Threading.Timer, can I just have the code to run inside the...
4
11122
by: Liverpool fan | last post by:
I have a windows application written using VB .NET that encompasses a countdown timer modal dialog. The timer is a System.Timers.Timer with an interval of 1 second. AutoReset is not set so accepts the default of True. The Elapsed event handler updates the dialog box with how long before it will close, acting as a timer itself. The dialog has a time to close property which is checked every time the Elapsed event fires. The problem I have...
5
12240
by: Tony Gravagno | last post by:
I have a class that instantiates two Timer objects that fire at different intervals. My class can be instantiated within a Windows Form or from a Windows Service. Actions performed by one of the event handlers may take longer than the interval for either of the timers, so it's possible for multiple events to fire "simultaneously" and for events to queue up. I'm attempting to get the timers to sync on some reference type object, or use...
2
2113
by: BobAtVandy | last post by:
I'll greatly appreciate any help on this. Actually 2 questions: 1. I believe I need to use the Windows timer System.Timers.Timer . The examples I find on the web all access that timer by 'import System' . (That's System with a capital S.) I have pywin32 installed and 'import System' doesn't find System so I gather it's not in that package. Where does one get the package with Windows' System class? 2. The reason I've been...
8
3370
by: Ollie Riches | last post by:
I'm looking into a production issue related to a windows service and System.Timers.Timer. The background is the windows service uses a System.Timers.Timer to periodically poll a directory location on a network for files and then copies these files to another location (on the network) AND then updates a record in the database. The file copying is performed before the database update because the file system is not transactional. The code...
0
8872
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9392
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9246
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9091
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4505
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4773
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3211
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2619
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2150
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.