org.sonar.plugins.csharp.S4583.html Maven / Gradle / Ivy
Why is this an issue?
When calling the BeginInvoke
method of a delegate,
resources are allocated that are only freed up when EndInvoke
is called. Failing to pair BeginInvoke
with
EndInvoke
can lead to resource leaks and incomplete asynchronous calls.
This rule raises an issue in the following scenarios:
- 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
does not contain a call to EndInvoke
in the same block.
How to fix it
Code examples
Noncompliant code example
BeginInvoke
without callback:
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
}
BeginInvoke
with callback:
public delegate string AsyncMethodCaller();
public static void Main()
{
AsyncExample asyncExample = new AsyncExample();
AsyncMethodCaller caller = new AsyncMethodCaller(asyncExample.MyMethod);
IAsyncResult result = caller.BeginInvoke(
new AsyncCallback((IAsyncResult ar) => {}),
null); // Noncompliant: not paired with EndInvoke
}
Compliant solution
BeginInvoke
without callback:
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(result);
}
BeginInvoke
with callback:
public delegate string AsyncMethodCaller();
public static void Main()
{
AsyncExample asyncExample = new AsyncExample();
AsyncMethodCaller caller = new AsyncMethodCaller(asyncExample.MyMethod);
IAsyncResult result = caller.BeginInvoke(
new AsyncCallback((IAsyncResult ar) =>
{
// Call EndInvoke to retrieve the results.
string returnValue = caller.EndInvoke(ar);
}), null);
}
Resources
Documentation
© 2015 - 2024 Weber Informatics LLC | Privacy Policy