-1

I'm trying to get more familiar with eventhanlders, but my current even only updates once, I want it to update until I close the application.

This is my code:

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

But like I said, it will only update once, I want it to update until I close my application. I know I can just do a While(true) but I rather not.

foo bar
  • 180
  • 3
  • 17
  • It should automatically update every time unless the object of the event changes. You have a null object so it is getting called one. Maybe try using 'this' instead of 'null'. – jdweng Oct 04 '15 at 10:49

3 Answers3

0

I think you want a Timer here:

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;

Specify callback:

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

Now every 2 seconds (or specify any other interval) callback OnTimedEvent will be called.

xZ6a33YaYEfmv
  • 1,816
  • 4
  • 24
  • 43
0

It is absolutely normal that your event is fired only once because the application starts only once. What you acctualy need is to set up a timer and do some work on its tick. Please have a look on example in answer for that question Simple example of the use of System. Timers. Timer in C#

Community
  • 1
  • 1
Festyk
  • 316
  • 1
  • 6
0

Well it only updates once since you only invoke it once (I don't really get the context where your code runs since you both declare a static variable and invokes it on the same scope which is impossible).

If you want something to occur periodically you should use Timer, or in some cases AutoResetEvent/ManualResetEvent.

EventHandlers should be used only when you work as event driven which mean you want your handler to invoke When something happens

Here an example for [System.Timers.Timer][2] with your handler:

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

Also you need Program_update's signature to look like that:

private void Program_updater(object source, ElapsedEventArgs e)
Tamir Vered
  • 10,187
  • 5
  • 45
  • 57