How to pass parameters to the function called by ElapsedEventHandler?
My code:
private static void InitTimer(int Index)
{
keepAlive[Index] = new Timer();
keepAlive[Index].Interval = 3000;
keepAlive[Index].Elapsed += new ElapsedEventHandler(keepAlive_Elapsed[, Index]);
keepAlive[Index].Start();
}
public static void keepAlive_Elapsed(object sender, EventArgs e[, int Index])
{
PacketWriter writer = new PacketWriter();
writer.AppendString("KEEPALIVE|.\\");
ServerSocket.Send(writer.getWorkspace(), Index);
ServerSocket.DisconnectSocket(Index);
}
What I want to do is between the brackets ([ and ]).
But just doing it like that obviously doesn’t work…
You can’t do this within the method itself – you have to make your event handler aware of its context, effectively. The simplest way of doing this is with a lambda expression or anonymous method:
Here, the anonymous method (the bit with the
delegatekeyword) has created a delegate which knows about theIndexparameter toInitTimer. It just calls theKeepAliveElapsedmethod. I’ve used the anonymous method syntax because you didn’t need the sender or event args; if you did need them I’d probably use a lambda expression instead, e.g.(Note that conventionally the
Indexparameter should be calledindex, btw.)