Dispose analysis
To reduce the number of resource leaks in your code and improve its performance, you need to ensure the correct handling of disposable resources. On the one hand, you want to enforce the
using
keyword at call sites of the specific APIs, but on the other hand, you don't want to have a lot of noise with false positives around each usage of
IDisposable
.
Therefore, to analyze the handling of disposable resources, JetBrains Rider relies on a set of annotation attributes from JetBrains.Annotations .
To start the analysis, annotate your critical disposable APIs with the [MustDisposeResource] attribute. You can use this attribute to annotate disposable types, their constructors, and factory methods. Once this is done, JetBrains Rider will report call sites that are not treating the resource as disposable and suggest the corresponding quick-fixes:
The warning will disappear as soon as you wrap the disposable resource in a
using
or explicitly call
Dispose()
on that resource.
As you can see on the screenshot above, usages of the
[MustDisposeResource]
are also marked with the corresponding
inlay hints
, which are configurable on the
page of JetBrains Rider settings
Ctrl+Alt+S
.
If your API does not expose the
Dispose()
method or have several methods that handle the disposal, you can annotate those methods that actually dispose resources with the
[HandlesResourceDisposal]
attribute:
If a custom dispose method expects a disposable resource as an argument, you can annotate the corresponding parameter with
[HandlesResourceDisposal]
:
Finally, if a method that obtains a resource from an annotated source does not handle resource disposal, but returns it to other callers, the problem of potential incorrect handling of the resource is passed to the callers. If this is deliberate, you can let the analyzer know that by annotating the method with
[MustDisposeResource]
to explicitly delegate the responsibility of handling the disposable resource to the callers: