I have a high priority thread which offers some events that tell about its actions:
public event EventHandler<EventArgs> Connecting;
private _MyMethod()
{
// ...some code
OnConnecting(my_event_args);
// ...more code
}
The thread should not be blocked by whatever processing is done within the subscriber's event processing method like that would happen with plain vanilla event handling:
protected virtual void OnConnecting(EventArgs e)
{
EventHandler<EventArgs> temp = Connecting; // for thread-safety
if (temp != null) temp(this, e); // execute subscriber within "my" thread
}
The first solution is to simply pass the event (delegate) as lambda to Task.Run
:
protected virtual void OnConnecting(EventArgs e)
{
EventHandler<EventArgs> temp = Connecting; // for thread-safety
if (temp != null) Task.Run(() => temp(this, e));
}
Do I err or is this implicitly sequencing all subscribers in a non-parallel order of execution, like calling them directly would have? Is that next version a sensible way of placing all subscribers in parallel into the Threadpool?
protected virtual void OnConnecting(EventArgs e)
{
foreach (var t in Connecting.GetInvocationList()) Task.Run(()=>t.DynamicInvoke(this,e));
}
Also, somewhere I read that lambdas aren't as performant as simply calling a delegate, is there a way to get rid of it or was the recommendation wrong?