88 lines
1.7 KiB
Plaintext
88 lines
1.7 KiB
Plaintext
== Why is this an issue?
|
|
|
|
It is possible in an ``++IDisposable++`` to call ``++Dispose++`` on class members from any method, but the contract of ``++Dispose++`` is that it will clean up all unmanaged resources. Move disposing of members to some other method, and you risk resource leaks.
|
|
|
|
|
|
This rule also applies for disposable ref structs.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,csharp]
|
|
----
|
|
public class ResourceHolder : IDisposable
|
|
{
|
|
private FileStream fs;
|
|
public void OpenResource(string path)
|
|
{
|
|
this.fs = new FileStream(path, FileMode.Open);
|
|
}
|
|
public void CloseResource()
|
|
{
|
|
this.fs.Close();
|
|
}
|
|
|
|
public void CleanUp()
|
|
{
|
|
this.fs.Dispose(); // Noncompliant; Dispose not called in class' Dispose method
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
// method added to satisfy demands of interface
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,csharp]
|
|
----
|
|
public class ResourceHolder : IDisposable
|
|
{
|
|
private FileStream fs;
|
|
public void OpenResource(string path)
|
|
{
|
|
this.fs = new FileStream(path, FileMode.Open);
|
|
}
|
|
public void CloseResource()
|
|
{
|
|
this.fs.Close();
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
this.fs.Dispose();
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
* CWE - https://cwe.mitre.org/data/definitions/459[CWE-459 - Incomplete Cleanup]
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Move this "Dispose" call into this class' own "Dispose" method.
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== relates to: S2930
|
|
|
|
=== on 22 May 2015, 09:52:57 Tamas Vajk wrote:
|
|
Removed the "noncompliant" comment from the compliant solution. Otherwise it looks good
|
|
|
|
endif::env-github,rspecator-view[]
|