简体   繁体   English

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

[英]C# Event execution order (Unity3D game)

I'm developing a game in Unity (C#) and I'm relying on C# events to update the game state (ie: check whether the game is completed after a given action). 我正在用Unity(C#)开发游戏,并且依靠C#事件来更新游戏状态(即:在执行给定操作后检查游戏是否完成)。

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 ABC ? 是否保证输出始终ABC Or could the event subscriber's execution ( HandleCellLetterSet () ) be delayed until the next frame resulting in ACB ? 还是可以将事件订阅者的执行( HandleCellLetterSet () )延迟到导致ACB的下一帧?


EDIT: B is the only subscriber of A.LetterSet . 编辑: BA.LetterSet的唯一订阅者。 The question is not about execution order between multiple subscribers. 问题不在于多个订户之间的执行顺序。

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. 因此,保证您的代码可以打印A,B,C。

More links: are C# events synchronous? 更多链接: C#事件是否同步? , making event asynchronous - Should I avoid 'async void' event handlers? ,使事件异步- 我应该避免使用“异步无效”事件处理程序吗? , awaiting for asynchronous events - Asynchronous events in C# . ,等待异步事件-C#中的异步事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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