V3114. IDisposable object is not disposed before method returns.
To understand what kind of issues this diagnostic detects, we should recall some theory.
The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used and there are no strong references to it left. However, it is not possible to predict when garbage collection will occur (unless you run it manually). Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams. Such resources are usually released using the 'Dispose' method.
The analyzer relies on that information and issues a warning when detecting a local variable whose object implements the 'IDisposable' interface and is not passed outside that local variable's scope. After the object is used, its 'Dispose' method is not called to release the unmanaged resources held by it.
If that object contains a handle (for example a file), it will remain in the memory until the next garbage-collection session, which will occur in an indeterminate amount of time up to the point of program termination. As a result, the file may stay locked for indefinite time, affecting normal operation of other programs or the operating system.
Consider the following example:
string Foo()
{
var stream = new StreamReader(@"C:\temp.txt");
return stream.ReadToEnd();
}
In this case, the 'StreamReader' object will be storing the handle of an open file even after control leaves the 'Foo' method, keeping that file locked to other programs and the operating system until the garbage collector cleans it up.
To avoid this problem, make sure you have your resources released in time by using the 'Dispose' method, as shown below:
string Foo()
{
var stream = new StreamReader(@"C:\temp.txt");
var result = stream.ReadToEnd();
stream.Dispose();
return result;
}
For more certainty, however, we recommend that you use a 'using' statement to ensure that the resources held by an object will be released after use:
string Foo()
{
using (var stream = new StreamReader(@"C:\temp.txt"))
{
return stream.ReadToEnd();
}
}
The compiler will expand the 'using' block into a 'try-finally' statement and insert a call to the 'Dispose' method into the 'finally' block to guarantee that the object will be collected even in case of exceptions.
This diagnostic is classified as:
You can look at examples of errors detected by the V3114 diagnostic. |