0
我在Unity(C#)中开发游戏,我依靠C#事件更新游戏状态(即:检查游戏是否在给定操作后完成)。C#事件执行顺序(Unity3D游戏)
考虑以下情形:
// 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
唯一订户。问题不在于多个订户之间的执行顺序。
您不能依赖从一个调用到下一个调用以任何特定顺序执行的处理程序。这真的很危险,并导致一个不可理解的代码路径。看看[事件链](https://www.codeproject.com/Articles/27406/Event-Chain),如果你真的需要。 – Smartis
谢谢@Smartis的参考。为了避免混淆,我正在编辑问题以明确代码仅包含一个事件订户。问题不在于多个订阅者之间的执行顺序,而是关于触发事件和订阅者执行代码之间的执行顺序。 –