Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use BeginInvoke with a MulticastDelegate?

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?

like image 843
Don Kirkby Avatar asked Jan 19 '11 01:01

Don Kirkby


People also ask

What is difference between event and delegate in c#?

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.

What is an event and a delegate?- how Are they Related?

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.

How Are events and delegates associated in the. net framework?

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.


1 Answers

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);
    }
}
like image 132
Don Kirkby Avatar answered Oct 27 '22 10:10

Don Kirkby