【发布时间】: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?
编辑:B 是A.LetterSet 的唯一订阅者。问题不在于多个订阅者之间的执行顺序。
【问题讨论】:
-
您不能依赖从一个调用到下一个调用以任何特定顺序执行的处理程序。这真的很危险,会导致无法理解代码的路径。看看Event Chains,如果你真的需要的话。
-
感谢@Smartis 的参考。为了避免混淆,我正在编辑问题以明确代码仅包含一个事件订阅者。问题不在于多个订阅者之间的执行顺序,而在于触发事件的行为和订阅者中执行代码之间的执行顺序。
标签: c# ios events unity3d thread-safety