0

I'm developing a game in Unity (C#) and I'm relying on C# events to update the game state (i.e.: check whether the game is completed after a given action).

Consider the following scenario:

// model class
class A
{
    // Event definition
    public event EventHandler<EventArgs> LetterSet;
    protected virtual void OnLetterSet (EventArgs e)
    {
        var handler = LetterSet;
        if (handler != null)
            handler (this, e);
    }

    // Method (setter) that triggers the event.
    char _letter;
    public char Letter {
        get { return _letter }
        set {
            _letter = value;
            OnLetterSet (EventArgs.Empty);
        }
    }
}

// controller class
class B
{
    B ()
    {
        // instance of the model class
        a = new A();
        a.LetterSet += HandleLetterSet;
    }


    // Method that handles external (UI) events and forward them to the model class.
    public void SetLetter (char letter)
    {
        Debug.Log ("A");
        a.Letter = letter;
        Debug.Log ("C");
    }

    void HandleCellLetterSet (object sender, EventArgs e)
    {
        // check whether the constraints were met and the game is completed...
        Debug.Log ("B");
    }
}

Is it guaranteed that the output will always be A B C? Or could the event subscriber's execution (HandleCellLetterSet ()) be delayed until the next frame resulting in A C B?


EDIT: B is the only subscriber of A.LetterSet. The question is not about execution order between multiple subscribers.

Eduardo Coelho
  • 1,953
  • 8
  • 34
  • 60
  • 1
    You cannot rely on the handlers being executed in any particular order from one invocation to the next. This is really dangerous and leads to a path of not understandable Code. Look at [Event Chains](https://www.codeproject.com/Articles/27406/Event-Chain), if you really have to. – Smartis has left SO again Apr 19 '17 at 14:35
  • 1
    Thank you @Smartis for the reference. In order to avoid confusion, I'm editing the question to make clear that the code contains only one event subscriber. The question is not about the execution order between multiple subscribers, it is about the execution order between the act of triggering the event and executing code in subscribers. – Eduardo Coelho Apr 19 '17 at 14:41

1 Answers1

1

Yes, synchronous event handlers as shown in the post are guaranteed to finish after executing sequentially (in some order - Order of event handler execution) before execution returns back to code that triggered event.

So your code is guaranteed to print A,B,C.

More links: are C# events synchronous?, making event asynchronous - Should I avoid 'async void' event handlers? , awaiting for asynchronous events - Asynchronous events in C#.

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179