Disposing / closing in c# - when to do it - c#

It has come to my attention that certain resources should be disposed of after utilizing them or closed etc;
Is there a rule of thumb as to what exactly should be closed / disposed?
Example - when you use StreamWriter , you want to close that when you are done to avoid errors etc. What are things that should absolutely be closed / disposed of and when?

The rule of thumb is... (drumroll, curtains pull back, pyrotechnics go up, and as the smoke clears)
Every time you are done using an object, if and only if the type1 implements System.IDisposable
Oh, you were expecting something complicated? Sorry to disappoint.
1The concrete type of the object. Sometimes that needs a runtime check, e.g. with IEnumerator implementations.

As #BenVoigt says, you should dispose of an IDisposable if you are done using that resource. C# introduced the using keyword for developers ease of use:
Example:
using (FileStream SourceStream = File.Open("file.ext", FileMode.Open)) {
//do something with the file
}
This keyword is a syntactical way to ensure that you dispose of your resource once you exit a method, etc. Of course some resources can be shared over multiple methods, threads, etc. so this language construct is not always available.
In many cases however, it's not that bad to forget to dispose of such object. If the program does no longer refers to it, the garbage collector will eventually walk by and dispose of it itself. Disposing of objects is however useful if the resource is large (a large file) or uses network resources (e.g.: a database connection). Since it releases resources that can be reused by other programs/users/clients/...
Furthermore disposing of objects is useful if they can be shared over multiple processes, threads, etc. like for instance files.: say you write to a file, then other programs need to wait until the write process has ended. If however program A waits for a file in use by process B and vice versa, a deadlock will occur: both programs wait for each other but don't give up their own resource. By disposing of such resources as soon as possible, most deadlocks will be prevented.

Related

What to do when lost stream blocks a file?

I've had this problem several times and until now not found a satisfying solution for it (restarting the computer is quite annoying if it takes 15 min to do so...):
When programming something with files, you have to use filestreams. The problem with them is (at least in C#) that they need to release the file again before you can access it from another place. As this is of course a good idea most of the time, it happened to me a few times that I forgot to release the file in the process of programming and debugging or the program crashed before the stream could be closed.
Is there any way to find and kill those streams using windows features or something like that? Problems like that occured in C# as well as in C++ (or C, I am not sure anymore).
From the answers I read, that this should not occur when the stream is handled properly. But what if I was to dumb to handle it right and the stream is not closed properly (because of whatever reason)? Is there a way to fix this while the PC is running?
This should not be a problem.
When your application is running normally, you use a using block to ensure that unmanaged resources like these are properly released. This is necessary for any object that implements the IDisposable interface.
If that fails, the operating system will jump in and save your bacon. The OS automatically releases any file handles that a process had open when it terminates, so even if your application crashes, there is no issue.
Anything that implements the IDisposable interface (which includes Streams) should always be either enclosed in a using block or be a member of a class which in turn implements IDisposable itself (and the new Dispose() method will also call the member's Dispose() method). There ought to be a compiler warning for this, imo.
Do this, and your file locks will be released properly.

Do I have to use a “using” statement in a short method?

Do I have to use a using statement to dispose immediately even in a method? Or will the ending of the method cause an automatic Dispose of all local variables including graphics?
(I’m asking this because I’ve seen examples that have Dispose calls at the end of methods, and wanted to know if that’s really necessary.)
Thanks.
Yes, you do. Going out of scope does not do anything; it does not call Dispose(), it does not garbage-collect, it does not call a finalizer.
If the type is IDisposable, then yes. It is your job to tidy up after yourself (assuming that the object is actually "done with" at this point).
Possible side-effects of not doing this:
files get left open and cause access-exceptions (FileStream)
connections get left open and cause pool saturation (DbConnection)
unmanaged handles get saturated and cause resource starvation (any winforms/etc)
transactions get left open and cause blocking (TransactionScope / DbTransaction)
etc
basically, bad things.
Furthermore, in most cases where you see Dispose() at the bottom of the method, a using would be preferable. There are some cases where that isn't possible (fields on an object, for example), but the point remains: it sounds like those are bad examples.
You don't ever have to dispose of an object. But if you want to release unmanaged resources earlier rather than whenever the GC gets around to it (which is when it processes the fReachable queue) then yes you should since the scope of of a method does not determine when a disposable object's finalize will be called.
For more you might want to read Jeffrey Richter's Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework
As delnan noted if there's a hard limit to the resources you're using you're much more likely to impacted if you let it get reclaimed by the GC rather than calling Dispose. DB connections are a good example of this kind of reasource and is certainly the reason why the NumberOfReclaimedConnections performance counter got created.
Yes, use using. It is a great statement.
Actually if you don't call Dispose (either manually or by using using), you can end up in a situation where your managed memory is stil quite empty, but unmanaged resources are depleted. Eventually it can cause a deadlock because other objects or other processes will wait for your unmanaged resources and you will wait for them. (Garbage collector won't run, because managed memory still won't be full.)
So please call Dispose as soon as you can. Once you don't need an object which has got that method defined, call it.

Do I need to dispose of a resource which is not actually used?

i have a stupid question, but i want to hear the community here.
So here is my code:
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
return true;
}
My question, is it any different than:
(FtpWebResponse)request.GetResponse();
return true;
Which one is better in general? which one in terms of GC and why?
The first is better, but not in terms of GC. WebResponse implements IDisposable because it has resources that need to be released such as network connections, memory streams, etc. IDisposable is in place because you, as the consumer, know when you are done with the object and you call Dispose to notify the class you're done with it, and it is free to clean up after itself.
The using pattern really just calls Dispose under the hood. E.g. your first example is actually compiled to be this:
FtpWebResponse response = (FtpWebResponse)request.GetResponse()
try
{
}
finally
{
((IDisposable)response).Dispose();
}
return true;
This is separate from the garbage collector. A class could also clean up resources in the finalizer, which gets called from GC, but you should not rely on that to happen for two reasons:
It could be a very long time before GC finally comes around, which means those resources are sitting there being consumed for no good reason.
It might not actually clean up resources in the finalizer anyway
The first one is better.
The difference is that the using statement will call dispose on the object wrapped in it. It will correctly dispose of held resources.
From MSDN, the using statement:
Provides a convenient syntax that ensures the correct use of IDisposable objects.
I appreciate that you are not interested in the response. However, the response object has been created, initialised and returned to your code whether you wanted it or not. If you don't dispose it, then it will hang around consuming resources until the GC eventually gets round to finalizing it.
I agree with what others said, but if you have such hate for the using() syntax, you could do:
((IDisposable)request.GetResponse()).Dispose();
return true;
The GC doesn't care about anything other than memory, so if you've got plenty of memory and are not consuming much of it, it might be a very long time until it does a GC. During that entire time the unmanaged resources, such as network connections, file handles, database connections, graphics handles etc., remain tied up by the objects that are waiting to be GC'd. This can cause you to run out of these resources and the GC will be oblivious because it doesn't monitor unmanaged resources.
So if you put your code in a loop and kept calling it, without calling Dispose, you might find it quickly degrades in performance(processes fighting for scarce resources) or gives you an exception due to a lack of the unmanaged resources. It depends on the context of how it is being called and how you are creating other related objects. Rather than analyze each situation, it is always safest to call Dispose as soon as you are done with the instance.
It is true that eventually Dispose will be called by the GC on an object that has gone out of scope/is no longer referenced, but this is indeterministic. Being indeterministic, you could see different results in how soon resources are free'd when testing vs production and lead to random Exceptions for failure to allocate resources when they run out. If you could choose between consistent deterministic behavior of your application and inderterministic, you'd probably want deterministic, unless maybe you are trying to confuse your Testers.

C# Do I Need Socket.Close()?

I am studying asynchronous C# Sockets at the moment and i have noticed something that i am confused about.
In all the End...(Accept/Connect) etc there is a code section like:
Socket s = (Socket) ar.AsyncState;
Here it is being casted as a socket.
As each End uses these local Sockets is there any point in trying to close() any of them once I am done?
What is the best practice?
Most authors seem to agree that if something implements IDisposable, you should call Dispose. The easiest way to do this is to use 'using' which automatically calls Dispose for you.
using (DirectoryEntry de = new DirectoryEntry(path))
{
.... some code
}
I think the best practice for sockets is similar to that for the streams. I personally always use the close() methods in both - sockets and streams. If something has been opened, it should be properly closed :)
It will get closed eventually even if you don't (when the garbage collector kicks in), however best practices dictates that you close handles to objects when you no longer need them.
Consider file streams, not closing a file stream can mean that data will not be wrote to a file. Sutble problems like this can occur if you do not explicity close the handle of objects that should be closed.
Closing your sockets is critical. Just because you don't notice any ill effects in a particular Framework version doesn't mean in future implementation the Framework might leave resources in use until it is closed. You most likely are leaving resources in use on the system as well. Plus, it doesn't hurt. :p
The object probably does free its resources and implictly close the socket when it is destroyed, but with a automatic garbage collected environment like C#, you never know when that might happen.
Either by using the
using(Socket s)
{
...
}
or by using socket open and at the end closing the socket.
If you leave a socket opened and try to open it again somewhere else then a runtime error will occur...
All streams dataReaders, connections must be closed.
the main reasons seem to be:
1. security
2. waste of memory
3. prone to runtime errors
I suggest either Disposing or Closing the stream after you are done. This allows the system to immediately free the network resources once you are done with your socket.
If you are using the socket from a single function, the using statement works well as it implicitly disposes your object. Otherwise (for example when keeping a socket active, maintaining a reference to it in an object), you will want to either call Close() or Dispose() when you are done. Otherwise, the socket could stay open indefinitely. Dispose() may be a slightly better choice because it frees more resources than a Close() would.
MSDN may skip the Close because the socket will be automatically closed at the termination of the process when the remaining resources are garbage collected.
Socket.Close calls Dispose. Calling Dispose, either explicitly or implicitly, on an IDisposable object is obligatory. The IDisposable interface is for objects that use unmanaged resources, so allowing the object to be garbage collected without calling dispose will result in resource leaks. A short sample program may not show this problem, but a full, long running problem will certainly run into problems.

What's the purpose of implementing the IDisposable interface?

What's the purpose of implementing the IDisposable interface? I've seen some classes implementing it and I don't understand why.
If your class creates unmanaged resources, then you can implement IDisposable so that these resources will be cleaned up properly when the object is disposed of. You override Dispose and release them there.
When your classes makes use of some system resource, it's the class' responsibility to make sure the resource is freed too. By .Net design you're supposed to do that in the Dispose method of the class. The IDisposable interface marks that your class needs to free resource when it's no longer in use, and the Dispose method is made available so that users of your class can call it to free the consumed resources.
The IDisposable method is also essential if you want auto clean-up to work properly and want to use the using() statement.
As well as freeing unmanaged resources, objects can usefully perform some operation the moment they go out of scope. A useful example might be an timer object: such objects could print out the time elapsed since their construction in the Dispose() method. These objects could then be used to log the approximate time taken for some set of operations:
using(Timer tmr=new Timer("blah"))
{
// do whatever
}
This can be done manually, of course, but my feeling is that one should take advantage wherever possible of the compiler's ability to generate the right code automatically.
It all has to do with the garbage collection mechanism. Chris Sells describes garbage collection, finalizers, and the reason for the Dispose pattern (and the IDisposable interface) episode 10 of .NET Rocks! (starting about 34 minutes in).
Many objects manipulate other entities in ways that will cause problems if not cleaned up. These other entities may be almost anything, and they may be almost anywhere. As an example, a Socket object may ask another machine to open up a TCP connection. That other machine might not be capable of handling very many connections at once; indeed, it could be a web-equipped appliance that can only handle one connection at a time. If a program were to open a socket and simply forget about it, no other computer would be able to connect to the appliance unless or until the socket got closed (perhaps the appliance might close the socket itself after a few minutes of inactivity, but it would be useless until then).
If an object implements IDisposable, that means it has the knowledge and impetus required to perform necessary cleanup actions, and such actions need to be performed before such knowledge and impetus is lost. Calling IDisposable.Dispose will ensure that all such cleanup actions get carried out, whereupon the object may be safely abandoned.
Microsoft allows for objects to request protection from abandonment by registering a method called Finalize. If an object does so, the Finalize method will be called if the system detects that the object has been abandoned. Neither the object, nor any objects to which it holds direct or indirect references, will be erased from memory until the Finalize method has been given a chance to run. This provides something of a "backstop" in case an object is abandoned without being first Disposed. There are many traps, however, with objects that implement Finalize, since there's no guarantee as to when it will be called. Not only might an object be abandoned a long time before Finalize gets called, but if one isn't careful the system may actually call Finalize on an object while part of it is still in use. Dangerous stuff. It's far better to use Dispose properly.

Categories

Resources