Hsu Wei Cheng
Hsu Wei Cheng

Reputation: 305

c# EventHandler depends on state transitions

I'm doing a system which monitors the states all the time by pooling mechanism. Once a state shifts to another state, do something to further process.

I came up with a good idea is EventHandler, depends on the state transition. But I found that it could be a lot of conditions to identify state transition.

(For example, Initial -> On, On -> Off, On -> Maintaining, Maintaing -> On, ...)

Is there a good way to improve this problem? or any suggestions? Thanks!

class StateMonitor
{
    public delegate void Mydelegate();
    public event Mydelegate SomethingHappened;
    public string _state;
    public StateMonitor()
    {
        SomethingHappened += new Mydelegate(monitor);
        _state = "Initial";
    }
    public string state
    {
        get
        {
            return this._state;
        }
        set
        {
            string temp = value;
            if (SomethingHappened != null)
            {
                if(this.state =="Initial" &&  temp =="On") //state transition
                SomethingHappened();
            }
        }
    }
    public void monitor()
    {
        Console.WriteLine("Happened");
    }
}

Upvotes: 1

Views: 988

Answers (2)

David Basarab
David Basarab

Reputation: 73341

What are really looking for is a state machine. For example can you just go from on to off?

Here is an answer to get your started on a state machine.

The issue with the way you have implemented with 1 delegate is each state will start to make the method doing the work larger. At some point in the future that method will not be able to be maintained, you can avoid that now with a different design.

Upvotes: 1

Edper
Edper

Reputation: 9322

Maybe an enum perhaps for your States and a change of the signature for your Delegate to deal the transition like:

class StateMonitor
{
    public enum States { initial, on, off, maintaining };
    public delegate void Mydelegate(States stFrom, States stTo);
    public event Mydelegate SomethingHappened;
    public States _state;

    public StateMonitor()
    {
        SomethingHappened += new Mydelegate(monitor);
        _state = States.initial;
    }
    public States state
    {
        get
        {
            return this._state;
        }
        set
        {
            if (SomethingHappened != null)
            {
                SomethingHappened(this._state, value);
            }
            _state = value;
        }
    }
    public void monitor(States stateFrom, States stateTo)
    {
        if (stateFrom == States.initial && stateTo == States.on)
        {
            // Do something for from Intitial state to On State
        }
        else if (stateFrom == States.on && stateTo == States.off)
        {
            // Do something for from On state to Off State
        }
        //... the rest of the code here
    }
}

Upvotes: 0

Related Questions