Forms.Timer start & Threads

A

Anatoli

I've got an incrementTimer()-Function, which is called on mous click.
It increments Windows.Forms.Timer interval and starts the timer... No
problem so far.

Now I want to do the same when IR-remote button is pushed. Therefore
I've got a component in my project, which fires an event when user
pushes the button on his control. No problem so far either.

When I get the event from the remote, I start incrementTimer-Function
in exactly the same way as when mouse button is pushed (just calling
incrementTimer())

The first problem was, that an update to textBox.Text inside
incrementTimer() wasn't threadsafe anymore, but I solved this
following msdn instructions exactly:

// This delegate enables asynchronous calls for setting
// the text property on a TextBox control.
delegate void setButtonTextCallback(string text);

// If the calling thread is different from the thread that
// created the TextBox control, this method creates a
// setButtonTextCallback and calls itself asynchronously using
the
// Invoke method.
//
// If the calling thread is the same as the thread that
created
// the TextBox control, the Text property is set directly.
private void setButtonText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.button.InvokeRequired)
{
setButtonTextCallback d = new
setButtonTextCallback(setButtonText);
this.Invoke(d, new object[] { text });
}
else
{
this.button.Text = text;
}
}

the text updates perfectly, but my problem is that I do not receive
any Timer_Tick events anymore, although there is a call to
timer.Start() inside incrementTimer() and with mouse click it works
perfectly.

Very upset by this... please help
 
A

Anatoli

Found out how to solve this!

You (actually I :) have to use System.Timers.Timer instead of
System.Windows.Forms.Timer (the second one manages only single-
threaded applications)

look here: http://msdn2.microsoft.com/en-us/library/tb9yt5e6.aspx

programatically it almost doesn't make any difference

in VisualStudio you can add System.Timers.Timer to your toolbar by
clicking Add/Remove Toolbox Items on the Tools menu

hope it healps someone
 
M

Morten Wennevik [C# MVP]

Hi Anatoli,

The safest bet is to use System.Threading.Timer as the System.Timers.Timer
may stop firing events in windows services. Only use Forms.Timer for
simple events where you don't need all the ticks (if the tick is unable to
reach your event handler it will get eaten by windows).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top