2017-04-19 111 views
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


編輯:BA.LetterSet唯一訂戶。問題不在於多個訂戶之間的執行順序。

+1

您不能依賴從一個調用到下一個調用以任何特定順序執行的處理程序。這真的很危險,並導致一個不可理解的代碼路徑。看看[事件鏈](https://www.codeproject.com/Articles/27406/Event-Chain),如果你真的需要。 – Smartis

+1

謝謝@Smartis的參考。爲了避免混淆,我正在編輯問題以明確代碼僅包含一個事件訂戶。問題不在於多個訂閱者之間的執行順序,而是關於觸發事件和訂閱者執行代碼之間的執行順序。 –

回答