Let's say I have 2 subscribers, is there a way to ensure that the second subscriber is done executing first before running the 1st subscriber. Easiest is probably add the 2nd subscriber first but is there another way to do this?
delegatePublisher = subscriber1; delegatePublisher = subscriber2;
CodePudding user response:
Under the hood, the compiler is using the MulticastDelegate class when you use the delegate keyword. The delegates are called synchronously (one after another) in the order they were added. However, if you need to strictly enforce execution order, relying on the under-the-hood execution order isn't the approach I would take. It is too easy to add the handlers out of order.
To add order to the delegate calls, consider creating two delegates instead of one - notifyFirst and notifySecond. Then, you can definitively control the order in your code in a robust manner without depending on the handlers being added in the right sequence at runtime.
CodePudding user response:
As John has already said events are executed synchronously. I would not rely on the order either. You can do something like this to enforce execution order.
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; } = () => { };
}
You can do the same with delegates if you want Action has just been shorter to write for the sample. SortedSet does not allow duplicates so only one item with the same ExecutionOrder number can exist. You could use SortedList or just anything and order it after the fact. I think SortedSet is fine and you probably should throw and Exception if the key already exists and not silently ignore it. If you have two with the same key you again don´t know for sure which one executes first.
