C#EvenHandler只更新一次

时间:2015-10-04 10:42:40

标签: c#

我正在尝试更熟悉eventhanlders,但我目前只更新一次,我希望它更新,直到我关闭应用程序。

这是我的代码:

private static event EventHandler Updater;
Updater += Program_updater;
Updater.Invoke(null, EventArgs.Empty);
Application.Run();


private static void Program_updater(object sender, EventArgs e)
{
    KeyUtils.Update();
    Framework.Update();
}

但就像我说的,它只会更新一次,我希望它更新,直到我关闭我的应用程序。我知道我可以做一会儿(真的),但我不愿意。

3 个答案:

答案 0 :(得分:0)

我想你想要一个Timer

Timer aTimer = new System.Timers.Timer(2000);

// Hook up the Elapsed event for the timer. 
aTimer.Elapsed += Program_updater;

// Have the timer fire repeated events (true is the default)
aTimer.AutoReset = true;

// Start the timer
aTimer.Enabled = true;

指定回调:

private void Program_updater(Object source, System.Timers.ElapsedEventArgs e)
{
    KeyUtils.Update();
    Framework.Update();
}

现在每2秒(或指定任何其他间隔)将调用回调OnTimedEvent

答案 1 :(得分:0)

由于应用程序仅启动一次,因此您的事件仅被触发一次是绝对正常的。 你需要的是设置一个计时器并做一些工作。 请查看该问题Simple example of the use of System. Timers. Timer in C#

的答案中的示例

答案 2 :(得分:0)

它只更新一次,因为你只调用一次(我没有真正得到你的代码运行的上下文,因为你们都声明了一个静态变量并在相同的范围内调用它是不可能的)。

如果您希望某些内容定期发生,您应该使用Timer,或者在某些情况下使用AutoResetEvent / ManualResetEvent

EventHandler只应在event driven工作时使用,这意味着您希望处理程序调用 当事情发生时

以下是[System.Timers.Timer][2]与您的处理程序的示例:

//Invoke every 5 seconds.
Timer timer = new Timer(5000);

//Add your handler to the timer invocation list.
timer.Elapsed += Program_updater;

//Start the timer.
timer.Start();

此外,您需要Program_update的签名:

private void Program_updater(object source, ElapsedEventArgs e)
相关问题