I want to raise a series of events from my library class, but I'm worried that some event subscribers will be rude and take a long time to process some events, thus blocking the thread that is raising the events. I thought I could protect the raising thread by using a thread pool thread to raise each event:
if (packet != null && DataPacketReceived != null)
{
var args = new DataPacketEventArgs(packet);
DataPacketReceived.BeginInvoke(this, args, null, null);
}
That works fine when there's only one subscriber to the event, but as soon as a second subscriber arrives, DataPacketReceived
becomes a multicast delegate, and I get an argument exception with the error message, "The delegate must have only one target." Is there an easy way to raise the event on a separate thread, or do I have to start a thread and then raise the event from there?
An event is declared using the event keyword. Delegate is a function pointer. It holds the reference of one or more methods at runtime. Delegate is independent and not dependent on events.
Delegate is a type that defines a signature and holds a reference of method whose signature matches with the delegate. Event is a notification raised by an object to signal the occurrence of an action. Delegate is associated with the event to hold a reference of a method to be called when the event is raised.
NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed: A delegate that identifies the method that provides the response to the event. Optionally, a class that holds the event data, if the event provides data.
I found a similar question on another site, and of course Jon Skeet had answered it. For my scenario, I chose to raise the event for each subscriber on 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With