views:

439

answers:

3

This page in the MS documentation, covering asynchrony in Windows Forms applications, states:

You can call EndInvoke to retrieve the return value from the delegate, if neccesary, but this is not required. (emphasis added)

This page covering the general case of asynchronous delegates, states something different:

No matter which technique you use, always call EndInvoke to complete your asynchronous call.

These two seem to be in direct conflict.

Which is true? Can someone explain?

see also, a post by Phil Haack.

Related: Is EndInvoke optional, sort-of optional, definitely not optional?

+8  A: 

Both are true - they're different calls.

In general you should always call EndInvoke to ensure that any resources acquired by the asynchronous call are released.

However, the Windows Forms team has guaranteed that you don't need to do this for Control.Invoke. You may well need to do it for other implementations of ISynchronizeInvoke though.

Jon Skeet
I agree with most of your answer, except the comment that they are "different calls." They don't seem to be different calls at all. Are they not both discussing EndInvoke on asynch delegates? It's just that the EndInvoke on the control delegates are a special case.
Cheeso
@Cheeso: No - Control.BeginInvoke isn't a call *on* a delegate at all. It *takes* a delegate.
Jon Skeet
+8  A: 

Unless the documentation for an interface explicitly says otherwise you must call EndInvoke for every place you call BeginInvoke. The primary reason is that EndInvoke is the only time where the owner can safely free certain resources that may be allocated for the BeginInvoke call (such as a WaitHandle).

But there are exceptions to this rule. APIs such as Control.BeginInvoke do not require an EndInvoke but it's explicit in the documentation.

JaredPar
A: 

I've used the fire-and-forget method with delegates before where the results were "useful if available, but not required". Just remember that you have no completion guarantees with that method. In particular, here's one place that I use it:

  • Start a delegate to check for application updates
  • Delegate begins a web request with a timeout
  • If an error/timeout occurs, or if the application is up-to-date, the method simply returns
  • If the application is out of date, I place a non-focus-stealing systray message stating so (no systray icon unless the update is available)

Either way, the application continues uninterrupted.

280Z28