Part of my program receives input over a network connection, and sends a message back. I want to limit the number of times a certain input can trigger a message, so the program can't be overloaded.
I have a background worker that waits for the input, and then when it receives the certain input, it calls into a static class that will determine if it has been enough time since the last input. I'm using a
System.Windows.Forms.Timer
To do this. It looks like this (everything is public so I can debug):
public static class InputResponse
{
public static System.Windows.Forms.Timer Time = new System.Windows.Forms.Timer();
public static void CreateTimer()//set all the properties of the timer
{
Time.Interval = 3000;
Time.Tick += new EventHandler(Time_Tick);
}
public static void InputAReceived()
{
if (Time.Enabled) //if the timer is running, do nothing
return;
else
{
//send response here
Time.Start();
}
}
public static void Time_Tick(object sender, EventArgs e)
{
Console.WriteLine("Time_Tick");
Time.Stop();
}
}
The problem is, the Time_Tick method never gets called from the timer. I can use Invoke() to trigger the method like so,
EventHandler testHandler = new EventHandler(InputResponse.Time_Tick);
testHandler.Invoke(sender, e);//triggered by a button
which writes to the console like it should, but just waiting for the timer doesn't work. It will send the response once, and then won't send it again, since the timer never gets stopped.
The ridiculous thing is I have it working almost exactly the same in another class. The only difference is that the timer is constantly running.
What am I missing?
One problem with your code is that it is using the System.Windows.Forms.Timer
class from a background thread and not associated with a window. This violates the instructions given in the documentation:
This timer is optimized for use in Windows Forms applications and must be used in a window.
For timers not related to GUI objects, use System.Timers.Timer
.
This may or may not be the cause of the problems you're having, but it's one thing you'll need to address for your code to work correctly.