Home > database >  How do I make use of a parameter in a ElapsedEventHandler (Timer)?
How do I make use of a parameter in a ElapsedEventHandler (Timer)?

Time:03-29

List<System.Timers.Timer> myTimers = new List<System.Timers.Timer>();
    
private void startFunction()
{    
    for (var parameter = 0; parameter < list.Count; parameter  )
    {
        System.Timers.Timer timer = new System.Timers.Timer(TimeSpan.FromMinutes(10).TotalMilliseconds);

        timer.Elapsed  = new ElapsedEventHandler(someFunction);
        timer.Start();
        myTimers.Add(timer);
    }
}

// without the int parameter this code works 
public void someFunction(object sender, ElapsedEventArgs e, int parameter) 
{
    // some code that have to run over time
}

So on the someFunction method I used a parameter (int) and without it, this is working out fine. I just want to send a parameter through this function and with searching online and trying different methods it still does not work.

Anyone having knowledge on how to send a parameter using the function someFunction every 10 minutes?

CodePudding user response:

Since parameter is just a local variable, you can create a lambda which captures this variable, and passes it to your someFunction method.

private void startFunction()
{    
    for (var parameter = 0; parameter < list.Count; parameter  )
    {
        var timer = new System.Timers.Timer(TimeSpan.FromMinutes((10)).TotalMilliseconds);

        int parameterCopy = parameter;
        timer.Elapsed  = (o, e) => someFunction(o, e, parameterCopy);
        timer.Start();
        myTimers.Add(timer);
    }
}

The parameterCopy is required because of this issue.

  • Related