I have the following event:
public static event Func<object, EventArgs, Task> Blocker;
I subscribe to it the following anonymous methods:
Blocker += async (x, y) => { await Task.Delay(20); Console.WriteLine("Task1"); };
Blocker += async (x, y) => { await Task.Delay(10); Console.WriteLine("Task2"); };
Blocker += async (x, y) => { await Task.Delay(5000); Console.WriteLine("Task3"); };
Blocker += async (x, y) => { await Task.Delay(1000); Console.WriteLine("Task4"); };
Now, if I invoke the event by writing await Blocker(null,null);
, this returns before all of the subscribed methods have returned, yet if I go down the long path of executing them, by doing the following:
foreach (var item in Blocker.GetInvocationList())
{
await ((Func<object, EventArgs, Task>)item)(null, null);
}
No such anomaly is seen.
What exactly is happening here? I thought under the hood, calling the event in turn uses a similar for-loop logic to go through the subscribed methods? I'm guessing it's due to the fact that the await keyword is working on the returned task of Blocker(null,null)
, and because that's an event, it gets confused and ends up doing the correct behavior, even though for me it looks wrong.