C# System.Windows.Forms.Timer 事件处理程序未被调用

C# System.Windows.Forms.Timer EventHandler not being called

我的部分程序通过网络连接接收输入,并发回消息。我想限制某个输入可以触发消息的次数,所以程序不能超载。

我有一个等待输入的后台工作程序,然后当它收到特定输入时,它会调用静态 class 来确定自上次输入以来是否有足够的时间。我正在使用

System.Windows.Forms.Timer

为此。它看起来像这样(一切都是 public 所以我可以调试):

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();
    }
}

问题是,Time_Tick 方法永远不会从计时器调用。我可以像这样使用 Invoke() 来触发方法,

    EventHandler testHandler = new EventHandler(InputResponse.Time_Tick);
    testHandler.Invoke(sender, e);//triggered by a button

它会像它应该的那样写入控制台,但只是等待计时器不起作用。它会发送一次响应,然后不会再次发送,因为计时器永远不会停止。

可笑的是,我在另一个 class 中几乎完全一样地工作。唯一的区别是计时器一直在 运行.

我错过了什么?

您的代码的一个问题是它使用来自后台线程的 System.Windows.Forms.Timer class 而不是与 window 相关联。这违反了 documentation:

中给出的说明

This timer is optimized for use in Windows Forms applications and must be used in a window.

对于与 GUI 对象无关的计时器,使用 System.Timers.Timer

这可能是也可能不是您遇到的问题的原因,但这是您需要解决的一件事,您的代码才能正常工作。