假設我有 2 個訂閱者,有沒有辦法確保在運行第一個訂閱者之前先完成第二個訂閱者的執行。最簡單的可能是先添加第二個訂閱者,但還有其他方法嗎?
委托發布者 = 訂閱者 1;委托發布者 = 訂閱者2;
uj5u.com熱心網友回復:
在后臺,當您使用委托關鍵字時,編譯器正在使用MulticastDelegate類。委托按照添加的順序被同步呼叫(一個接一個)。但是,如果您需要嚴格執行執行順序,那么依靠幕后執行順序不是我會采取的方法。亂序添加處理程式太容易了。
要為委托呼叫添加順序,請考慮創建兩個委托而不是一個 - notifyFirst 和 notifySecond。然后,您可以以穩健的方式明確控制代碼中的順序,而無需在運行時以正確的順序添加處理程式。
uj5u.com熱心網友回復:
正如約翰已經說過的那樣,事件是同步執行的。我也不會依賴訂單。你可以做這樣的事情來強制執行順序。
var sortedSet = new SortedSet<ActionWithExecutionOrder>(
Comparer<ActionWithExecutionOrder>.Create((x, y) =>
{
return x.ExecutionOrder.CompareTo(y.ExecutionOrder);
}));
sortedSet.Add(new ActionWithExecutionOrder
{
Action = () => Console.WriteLine("First added, should be executed second."),
ExecutionOrder = 2
});
sortedSet.Add(new ActionWithExecutionOrder
{
Action = () => Console.WriteLine("Second added, should be executed first."),
ExecutionOrder = 1
});
foreach(var actionWithExecutionOrder in sortedSet)
{
actionWithExecutionOrder.Action();
}
Console.ReadLine();
class ActionWithExecutionOrder
{
public int ExecutionOrder { get; set; }
public Action Action { get; set; } = () => { };
}
如果您希望Action為示例撰寫更短的時間,您可以對代表執行相同的操作。SortedSet不允許重復,因此只能存在具有相同 ExecutionOrder 編號的一項。您可以使用SortedList或只是任何東西,并在事后訂購。我認為SortedSet很好,Exception如果密鑰已經存在,您可能應該扔掉而不是默默地忽略它。如果您有兩個使用相同的密鑰,您再次不確定哪個先執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419865.html
標籤:
