Can I use BeginInvoke with MulticastDelegate?

I want to raise a series of events from my library class, but I am worried that some event subscribers will be rude and take a long time to process some events, thereby blocking the thread that raises events. I thought I could protect the rising thread using the thread pool thread to raise each event:

if (packet != null && DataPacketReceived != null) { var args = new DataPacketEventArgs(packet); DataPacketReceived.BeginInvoke(this, args, null, null); } 

This works fine when only one subscriber is present at the event, but as soon as the second subscriber DataPacketReceived , DataPacketReceived becomes a multicast delegate, and I get an argument exception with the error message: "The delegate should have only one target." Is there an easy way to raise an event in a separate thread, or do I need to start a thread and then raise an event from there?

+7
source share
1 answer

I found a similar question on another site , and of course John Skeet answered it. For my scenario, I decided to raise an event for each subscriber in a separate thread:

 if (packet != null && DataPacketReceived != null) { var args = new DataPacketEventArgs(packet); var receivers = DataPacketReceived.GetInvocationList(); foreach (EventHandler<DataPacketEventArgs> receiver in receivers) { receiver.BeginInvoke(this, args, null, null); } } 
+11
source

All Articles