Should we close HttpPostedFile.Inputstream, once we are done using it? - c#

I am uploading a file and directly feeding Inputstream to one of my objects. My Question is should we close and flush it once we are done processing it?

You don't need to explicitly close it, the resources allocated on your server are disposed when the request ends. See the final remark in the MSDN docs.
http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.aspx
However if the question is should you close it (or at least dispose of it) - then I'd say yes. Why not? It may release resources earlier than they would otherwise be released and you know you don't need them any more.

All objects that extend System.IO.Stream objects implement IDisposable. It would be best practice to put your Input stream in a using block, to ensure it is properly closed and disposed even in the event of an exception being thrown.

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.

Disposing / closing in c# - when to do it

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.

C# TCP Server Flush? [duplicate]

Note: I've read the following two questions already:
Can you explain the concept of streams?
C# using streams
I'm coding in C#
In almost all code samples that use streams, .Dispose(), .Flush(), .Close() are almost always called.
In the concept of a stream, what does accomplish?
If I don't dispose a stream that I stored in a variable, is my application leaking somewhere?
Why do I need to call any of these functions? I've seen code samples that don't do this and still get the job done (without an apparent breakage)
I'm currently building a class in my application that contains a primary method (lets call it GetStream()) that returns a stream via myWebRequest.GetResponse().GetResponseStream()
The primary method GetStream() returns a Stream object that can be used for any operation that requires a stream (StreamReader, Bitmap() etc.).
Is there a way to have the stream Disposed of automatically after its last use (garbage collected?) without forcing anyone that calls .GetStream() to manually dispose of it?
As you can probably tell, my questions are vague and general. My understanding of streams is not solid, so any links to helpful articles that offer a more in-depth look at streams than a SO question can offer would be appreciated.
Disposing a stream closes it (and probably doesn't do much else.) Closing a stream flushes it, and releases any resources related to the stream, like a file handle. Flushing a stream takes any buffered data which hasn't been written yet, and writes it out right away; some streams use buffering internally to avoid making a ton of small updates to relatively expensive resources like a disk file or a network pipe.
You need to call either Close or Dispose on most streams, or your code is incorrect, because the underlying resource won't be freed for someone else to use until the garbage collector comes (who knows how long that'll take.) Dispose is preferred as a matter of course; it's expected that you'll dispose all disposable things in C#. You probably don't have to call Flush explicitly in most scenarios.
In C#, it's idiomatic to call Dispose by way of a using block, which is syntactic sugar for a try-finally block that disposes in the finally, e.g.:
using (FileStream stream = new FileStream(path))
{
// ...
}
is functionally identical to
FileStream stream;
try
{
stream = new FileStream(path);
// ...
}
finally
{
if (stream != null)
stream.Dispose();
}

What is the point of streamwriters having Close() and Dispose()?

When you call Close on an active StreamWriter it makes it impossible to write any more code to the stream (since it's been closed). To open another stream, you have to make a new instance of a StreamWriter since there's no 'Open' method.
My question is, what's the point in having Close and Dispose when you can't really use anything besides Dispose after closing the stream?
I could understand if there was an Open function, i.e. you could close one file then open another using the same StreamWriter. But as there is only Close and you can't really use anything besides Dispose afterwards, why not just get rid of Close and have Dispose close the underlying stream as its first action?
I get that Dispose comes from IDisposeable and all that. What I want to know is why Close is needed specifically when Dispose appears to call Close anyway.
As far as I can see, without the ability to open another stream with the same StreamWriter, there is no point in having Close when you have no option but to Dispose afterwards since all other methods become useless.
Why is is that StreamWriter bothers having Close when they could merge Close and Dispose into a single method?
When dealing with streams there's a long standing convention that Close is a method that they have to close the stream. It's terminology that many programmers are used to and expect to see when dealing with streams. It would have been potentially confusing to have a stream without a Close method, and may have taken some time for people to realize that they should use Dispose to close the stream.
It's certainly possible for the class to have implemented IDisposable explicitly, so that the Dispose method wouldn't be there without a cast to IDisposable, and that my have cleaned up some of the confusion, but they choose not to do that and to leave two duplicate methods in the class.
It's entirely up to your personal preference whether you use Dispose or Close to close the stream.
According to the documentation, Close just calls Dispose with a value of true.
This method overrides Close.
This implementation of Close calls the
Dispose method passing a true value.
You must call Close to ensure
that all data is correctly written out to the underlying stream.
Following a call to Close, any operations on the StreamWriter might
raise exceptions. If there is insufficient space on the disk, calling
Close will raise an exception.
Dispose itself is inherited from IDisposable, which is used by classes that have resources that need to be released.
Opening a stream allocates both application and system resources. If your application opens many streams without closing them, then it restricts the ability of other applications to access those files. It's important that streams are closed as soon as possible.
As far as why streams don't have the ability to reopen, this is basically the .NET approach. The class represents an open stream. So create one to access the stream and get rid of it as soon as possible. When you want to access the stream again, you create another one.
I think it would be valid to create a stream class that could be reopened, but it does cause some problems as many of the methods wouldn't work when the stream was closed. In the end, a stream class really does represent an open stream.
Dispose is just there to make it easier to ensure the stream gets cleaned up in a timely manner.
why not just get rid of close and have dispose close the underlying stream as its first action?
It's good programming practice.
Suppose you have lights in your house that turn off automatically when you leave. You wouldn't have to turn off the lights when you left, but it's good practice. That way, you wouldn't require that every house you live in to automatically turn off the lights. You'd be in the habit of turning them off yourself.
Explicitly calling Close() tells the reader (and the system) "I'm done with this stream", and calling Dispose() tells the system (and the reader) "you can release any embedded resources".
You are on the right track when you say "why not just get rid of..." except it's backwards. If you look at the underlying code for StreamWriter.Close() you will see:
public override void Close()
{
this.Dispose(true);
GC.SuppressFinalize((object) this);
}
So the Close() method is just the way you would tell the framework that you are done writing to the stream.

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.

Categories

Resources