Search code examples
c#timer

Handling void type in Timer Event


I working on C#. I am using time class for making repetitive programs.

// Create a timer with a two second interval.
            aTimer = new System.Timers.Timer();
            // Hook up the Elapsed event for the timer. 
            aTimer.Elapsed += OnTimedEvent(iterations, dataItems);
            aTimer.Interval = Convert.ToDouble(initial_time)*1000;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;

 private ElapsedEventHandler void OnTimedEvent(Iterations iterations, byte[] dataItems)
    {
        Console.WriteLine("Scheduling start");
        Console.WriteLine("Writing on port");
        port.Write(dataItems, 0, dataItems.Length);

        msn = (string)iterations.msn;
        device_id = (int)iterations.device_id;
        p_id = (string)iterations.protocol_id;


    }

The error I am getting is

Severity Code Description Project File Line Suppression State Error CS0029 Cannot implicitly convert type 'void' to 'System.Timers.ElapsedEventHandler' CommunicationProfile F:\MDC Development\Scheduler\CommunicationProfile\CommunicationEngine.cs 465 Active

I don't want to return anything from the above method.

Any help would be highly appreciated.


Solution

  • Change

    private ElapsedEventHandler void OnTimedEvent(Iterations iterations, byte[] dataItems)
    

    To

    private void OnTimedEvent(Object sender, ElapsedEventArgs e)
    

    A method cannot have two return types, and the method that handles the Elapsed event must have this specific signature (you'll have to manage getting your data another way; it can't be passed via the parameters like the way you tried) though it can have any name. By signature we mean these arguments in (object and ElapsedEventArgs) and this return value (void)

    Note, you'll also need to remove the "parameters"/parentheses from the line where you attach the event handler. += just wants a method name in this context, not parameters. You don't get to specify the parameters because that's not how events work; events work by the person who wrote the Timer deciding what the arguments should be, both in terms of type and value (Microsoft deemed that an Elapsed handler shall have an object and an ElapsedEventArgs and they also decided that the object shall be the Timer itself and the ElapsedEventArgs shall be an instance that they make and set the properties on; you have near zero control over any of it)