Begin End Invoke
Calls to delegate's method "BeginInvoke" should be linked with calls to "EndInvoke"
What does this mean ?
When a delegate's BeginInvoke method is invoked, certain resources are allocated that are only released when EndInvoke is performed. This is why, to finish your asynchronous call, you should always couple BeginInvoke with an EndInvoke.
What can happen ?
This rule becomes problematic when:
- BeginInvoke is called without a callback and is not followed by a call to EndInvoke in the same block.
- A callback with a single argument of type IAsyncResult does not include an EndInvoke call.
Recommendation
To finish your asynchronous call, always pair BeginInvoke with EndInvoke.
References
Sample Code
Vulnerable :
public delegate string AsyncMethodCaller();
public static void Main()
{
AsyncExample asyncExample = new AsyncExample();
AsyncMethodCaller caller = new AsyncMethodCaller(asyncExample.MyMethod);
// Initiate the asynchronous call.
IAsyncResult result = caller.BeginInvoke(null, null); // Noncompliant - not paired with EndInvoke
}
Non Vulnerable :
public delegate string AsyncMethodCaller();
public static void Main()
{
AsyncExample asyncExample = new AsyncExample();
AsyncMethodCaller caller = new AsyncMethodCaller(asyncExample.MyMethod);
IAsyncResult result = caller.BeginInvoke(null, null);
string returnValue = caller.EndInvoke(out threadId, result);
}