Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must every BeginInvoke be followed by an EndInvoke?

Tags:

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?

like image 437
Cheeso Avatar asked Aug 13 '09 20:08

Cheeso


People also ask

Do I have to call EndInvoke?

As a matter of practice, you should call EndInvoke because the caller may have handlers subscribed to the events that may not matter to your processing, but may matter to the consumer so as to ensure certain kinds of processing can take place at a known time/application state.

What is BeginInvoke?

BeginInvoke(Action) Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on. BeginInvoke(Delegate) Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on.


2 Answers

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.

like image 69
JaredPar Avatar answered Sep 22 '22 18:09

JaredPar


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.

like image 29
Jon Skeet Avatar answered Sep 20 '22 18:09

Jon Skeet