Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using the System.Timers.Timer

Status
Not open for further replies.

1301621

Programmer
Nov 20, 2003
2
GB
Below is a sample of some of the code I have written to try to invoke a timer function that calls a specified method every time it elapses.
The method is Lights called by new ElapsedEventHandler. During execution, when this section of the code is reached it does not call the method Lights. I am looking for any suggestions for why this is so, or alternatively a version of code that utilises the timer function.

private Vehicle aVehicle;
private System.Timers.Timer aTimer;
private int simlength = 0;

System.Timers.Timer myTimer = new System.Timers.Timer();


public void LightTimer(Queue vehicleQueue)
{
Queue VQueue=vehicleQueue;
try
{
aTimer= new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(Lights);
aTimer.Interval = 1000;
myTimer.Enabled = true;
}
catch (Exception e)
{
Console.WriteLine("Due to a technical fault it was not possible to initialise traffic light timing sequence. "+e);
}
}
public void Lights(Object source, ElapsedEventArgs e)
{
simlength++;
if (simlength < 21)
this.LightSequence();
}

 
When you say new ElapsedEventHandler(Lights) is lights just the name of the event or is it a delegate?

Durkin
 
The aTimer object is going out of scope when try block is executed and so the creation of the object should not be in the try block.
Move aTimer= new System.Timers.Timer(); outside of the LightTimer() function and should get Elapse event rised after the interval.

-obislavu-

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top