【问题标题】:C# Event execution order (Unity3D game)C#事件执行顺序(Unity3D游戏)
【发布时间】:2017-04-19 14:26:59
【问题描述】:

我正在使用 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 的唯一订阅者。问题不在于多个订阅者之间的执行顺序。

【问题讨论】:

  • 您不能依赖从一个调用到下一个调用以任何特定顺序执行的处理程序。这真的很危险,会导致无法理解代码的路径。看看Event Chains,如果你真的需要的话。
  • 感谢@Smartis 的参考。为了避免混淆,我正在编辑问题以明确代码仅包含一个事件订阅者。问题不在于多个订阅者之间的执行顺序,而在于触发事件的行为和订阅者中执行代码之间的执行顺序。

标签: c# ios events unity3d thread-safety


【解决方案1】:

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

所以您的代码保证打印 A、B、C。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    相关资源
    最近更新 更多