Search code examples
c#windows-servicessystem.timers.timeraddhandler

CS0123 No overload for 'method' matches delegate System.Timers.ElapsedEventHandler


I'm converting an older VB windows service to C# .Net4.8.

I'm getting a CS0123 (No overload for 'method' matches delegate) error on the line that added a Handler for Timer.Elapsed converted from VB.Net which was:

AddHandler processTimer.Elapsed, New Timers.ElapsedEventHandler(AddressOf processTimer_Elapsed)

My C# code is:

protected override void OnStart(string[] args) 
{
    // Add code here to start your service. This method should set things
    // in motion so your service can do its work.

    processTimer = new System.Timers.Timer();

    //LINE BELOW GIVE CS0123 ERROR
    processTimer.Elapsed += new System.Timers.ElapsedEventHandler(processTimer_Elapsed);

    // Set up the timer to run for 30 seconds before starting the process proper
    processTimer.Interval = 30 * 1000;
    processTimer.AutoReset = false;
    processTimer.Enabled = true;

    processTimer.Start();

} //END OnStart

protected override void OnStop()
{
    //Add code here to perform any tear-down necessary to stop your service.
} //END OnStop

public void processTimer_Elapsed()
{
    processTimer.Stop(); // Stop the timer - we don't want it to fire again just yet

    ProcessRequests(); // Main processing code.

    // Reset the timer interval and restart the timer 
    processTimer.Interval = Settings.Default.timerInterval * 1000;
    processTimer.Start();

} // END processTimer_Elapsed()

public async void ProcessRequests()
{
    //Main code removed for brevity
}

I have searched for answers but come up blank... any help appreciated.


Solution

  • ElapsedEventHandler has the following signature:

    public delegate void ElapsedEventHandler(object? sender, ElapsedEventArgs e);
    

    That does not match the signature of processTimer_Elapsed, which you are attempting to use as the delegate.

    You have 2 options:

    Either change the signature of processTimer_Elapsed:

    public void processTimer_Elapsed(object? sender, ElapsedEventArgs e)
    {
    

    Or use an anonymous function to wrap the method call:

    processTimer.Elapsed
        += new System.Timers.ElapsedEventHandler(delegate { processTimer_Elapsed(); });