I have a programming problem which I think is being caused by my rustiness in using events and delegates…
I have the code:
public void DoStuff()
{
List<IProcess> processorsForService1 = processorsForService1 = ProcessFactory.GetProcessors();
foreach (IProcess p in processorsForService1)
{
if (p.ProcessTimer != null)
{
p.ProcessTimer.Elapsed += new ElapsedEventHandler(IProcess_Timer_Elapsed);
}
}
}
And:
private void IProcess_Timer_Elapsed(object sender, ElapsedEventArgs e)
{
IProcess p = (IProcess)sender;
p.Step_One();
p.Step_Two();
}
But when I get to the event handler im getting null reference exception for p on the first line.
How do I pass an argument to the handler in this instance?
It looks like you’re using a
System.Timers.Timer, if you were to use aSystem.Threading.Timerthen you could pass astateobject which, in this case, could be the desired instance of a class, i.e. the timer’s ‘owner’. In this way, you define your method body as with your previous experience of implementation within an event handler, only now the signature is as follows:Then, upon creating the timer instance, you can do something such as:
Then, use
timer.Change(whenToStart, interval)to kick off the timer.