Live Chat Icon For mobile
Live Chat Icon

How can I throw my events asynchronously?

Platform: WinForms| Category: Patterns

You can do so by calling BeginInvoke on your delegates. Unfortunately, you can’t call BeginInvoke() on the event member directly. You can invoke BeginInvoke()only if the delegate’s internal list of sink callbacks (actually other delegates) has only one target in it. If you have more than one, the delegate throws an exception. The workaround is to iterate over the event delegate internal invocation list, calling BeginInvoke() on everyone of them. You access the internal list using the GetInvocationList() method. Here is an example:


public delegate void NumberChangedDelegate(int num);

public class MySource
{
    public event NumberChangedDelegate m_NumberChangedEvent;

    public void FireEventAsynch(int num)
    {
        Delegate[] delegates = m_NumberChangedEvent.GetInvocationList();
        foreach (Delegate del in delegates)
        {
            NumberChangedDelegate sink = (NumberChangedDelegate) del;
            sink.BeginInvoke(num, null, null);
        }
    }

    public void FireEvent(int num)
    {
        m_NumberChangedEvent(num);
    }
}

From Juval Löwy at www.idesign.net; from his article in the .Net Insight online magazine at www.fawcette.com.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.