C#事件执行顺序(Unity3D游戏)

时间:2017-04-19 14:26:59

标签: c# ios events unity3d thread-safety

我正在开发Unity游戏(C#),我依靠C#事件更新游戏状态(即:检查游戏是否在给定动作后完成)。

考虑以下情况:

// 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");
    }
}

保证输出始终A B C?或者事件订阅者的执行(HandleCellLetterSet ())是否可以延迟到导致A C B的下一帧?

编辑:BA.LetterSet的唯一订阅者。问题不在于多个订户之间的执行顺序。

1 个答案:

答案 0 :(得分:1)

是的,帖子中显示的同步事件处理程序保证在执行之后按顺序执行(按某种顺序 - Order of event handler execution),然后返回到触发事件的代码。

因此,您的代码可以保证打印A,B,C。

更多链接:are C# events synchronous?,使事件异步 - Should I avoid 'async void' event handlers?,等待异步事件 - Asynchronous events in C#