Anonymous delegate vs Event handler for getting data from data thread to GUI thread

7 hours ago 2
ARTICLE AD BOX

I have a GUI that is subscribed to an event on a 3rd party library which lets the GUI know it should update. The 3rd party library fires the event on a thread that it spun up so I need to get back to the GUI thread to do things. I had implemented code like this

//in onload lib.JobDoneEvent += HandleJobDoneCompleteEvent; private void HandleJobDoneCompleteEvent(object sender, JobArgs args){ this.Invoke( (MethodInvoker) delegate{ UpdateWithData(sender, args); }); }

a coworker told me that the better practice would be to do something like this

private EventHandler<JobArgs> CompletionHandler; //In onload CompletionHandler = UpdateWithData; lib.JobDoneEvent += HandleJobDoneCompleteEvent; private void HandleJobDoneCompleteEvent(object sender, JobArgs args){ CompletionHandler?.Invoke(this, args); }

To me it seems like the latter would have more overhead due to needing to do a null check everytime the event fires at run time whereas the former would just have compiled the delegate at run time. It also feels odd to me to create an event handler to create an event from an event that would only be used with one method.

which is better/standard practice for moving data from one thread to the GUI thread and why? Is there a more standard/better practice that is different from either of these approaches?

Read Entire Article