Skip to content

Begin End Invoke

Calls to delegate's method "BeginInvoke" should be paired with calls to "EndInvoke"

What does this mean ?

Calling the BeginInvoke method of a delegate will allocate some resources that are only freed-up when EndInvoke is called. This is why you should always pair BeginInvoke with an EndInvoke to complete your asynchronous call.

What can happen ?

This rule raises an issue when: - the BeginInvoke method is called without any callback and it is not paired with a call to EndInvoke in the same block. - a callback with a single parameter of type IAsyncResult doesn't contain a call to EndInvoke.

Recommendation

You should always pair BeginInvoke with an EndInvoke to complete your asynchronous call.

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);
}