EventHandler call

I have the following EventHandler:

private EventHandler<MyEventArgs> _myEventHandler; public event EventHandler<MyEventArgs> MyEvent { add { _myEventHandler += value; } remove { _myEventHandler -= value; } } 

Can someone explain the difference between the following snippets?
Snippet EventHandler (A):

 //Snippet A: if (_myEventHandler != null) { _myEventHandler(new MyEventArgs()); } 

Snippet BeginInvoke (B):

 //Snippet B: if (_myEventHandler != null) { _myEventHandler.BeginInvoke(new MyEventArgs(), ar => { var del = (EventHandler<MyEventArgs>)ar.AsyncState; del.EndInvoke(ar); }, _myEventHandler); } 

To clarify: what is the difference between calling the EventHandler "as is" and using BeginInvoke ?

+7
source share
2 answers

BeginInvoke's BeginInvoke is async, which means it is being created in another thread. This can be dangerous if people do not expect this, and it is quite rare for events, but it can be useful.

Also, note that, strictly speaking, you must take a snapshot of the value of the event handler - this is especially true if (through Begin* ) you are dealing with streams.

 var tmp = _myEventHandler; if(tmp != null) { tmp(sender, args); } 

Also - note that the event subscription itself is not thread safe; again, this only matters if you are dealing with multi-threaded, but embedded field-like event safe for threads:

 public event EventHandler<MyEventArgs> MyEvent; // <===== done; nothing more 

Here you can avoid problems:

  • with the snapshot, we avoid the risk of the subscriber refusing the zero check and call (this means that they can receive an event that they did not expect, but that means we are not killing the upstream)
  • by changing the type of field we avoid the risk of losing / unsubscribing when two threads do this at the same time
+12
source

BeginInvoke() call immediately returns control to the calling thread and starts the delegate in a separate thread from ThreadPool , so this will be some kind of asynchronous execution.

+5
source

All Articles