简体   繁体   中英

Does the timer create new object when in the elapsed event?

I have an object A, which contains an event, is base class of class B, which contains a timer, like this:


public class A
{
    public event EventHandler<Status> StatusChanged;

    protected void StatusChangedEvent(Status e)
    {
         StatusChanged?.Invoke(this, e);
    }
}

public class B : A
{
    private System.Timers.Timer polling = new();

    public Beckhoff() : base()
    {
        pollingTimer.Elapsed += elapsedFunction;
        pollingTimer.Interval = 1000;
        pollingTimer.Start();
    }

    private void elapsedFunction(object source, ElapsedEventArgs e)
    {
        StatusChangedEvent(Status.Connected);
    }
}

If I subscribe something to the event

objB.StatusChanged += someFuction;

when i try to launch base event in the elapsedFunction, i cant because it is null, someFunction is deleted. It is like the elapsed event creates a copy of B object but without base parameters. Does the timer do this?

It might be that your timer is elapsed before you register the event handler.

Try this:

public class B : A
{
    private System.Timers.Timer polling = new System.Timers.Timer();

    public B() : base()
    {
        polling.Elapsed += ElapsedFunction;
        polling.Interval = 1000;            
    }

    private void ElapsedFunction(object source, ElapsedEventArgs e)
    {
        StatusChangedEvent(Status.Connected);
    }

    public void StartPolling()
    {
        polling.Start();
    }
}

And then, start polling after event registration:

var objB = new B();

objB.StatusChanged += ObjB_StatusChanged;

objB.StartPolling();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM