I'm looking into options for doing asynchronous event dispatching in a component that has many subscribers to its events. In perusing the options, I ran across this example:
public event ValueChangedEvent ValueChanged;
public void FireEventAsync(EventArgs e)
{
Delegate[] delegates = ValueChanged.GetInvocationList();
foreach (Delegate d in delegates)
{
ValueChangedEvent ev = (ValueChangedEvent)d;
ev.BeginInvoke(e, null, null);
}
}
Beyond the older syntax (the sample was from .NET 1.1), it looks to me like this is a serious resource leak. There's no completion method, no polling for completion, or any other way that EndInvoke
will be called.
My understanding is that every BeginInvoke
must have a corresponding EndInvoke
. Otherwise there are pending AsyncResult
object instances floating around, along with (potentially) exceptions that were raised during the asynchronous events.
I realize that it's easy enough to change that by supplying a callback and doing an EndInvoke
, but if I don't need to . . .
Handling the asynchronous exeptions is another matter entirely, and, combined with the need to synchronize with the UI thread (i.e. InvokeRequired
, etc.) could very well tank the whole idea of doing these asynchronous notifications.
So, two questions:
- Am I correct in believing that every
BeginInvoke
requires a correspondingEndInvoke
? - Beyond what I've noted above, are there other pitfalls to doing asynchronous event notifications in Windows Forms applications?