简体   繁体   中英

Do I need to dispose the FileStream object?

I am pretty depressed by my programming knowledge but do we really need to dispose FileStream Object ?

Reason I am asking is because code is throwing "File being used by another process" exception once in 100 cases and for a moment as if i try again(to download file using file stream) it works fine.

Please refer to this question for code.

Since it only happening once in 100 or so making me so confused and it's happening on production server so can't debug at all, but works perfectly on my development machine...

Of course, you need to dispose everything that is disposable, unless you have very good reason to not to dispose.

Put everything into a using block by default. If you call Close manually this is a code smell.

If a class implements IDisposable , then you should dispose it so any resources gets closed/cleaned up asap instead of relying on the garbage collector. Better yet, wrap it in a using block so it gets closed even if an exception occurs.

using (var stream = new FileStream(...))
{
   // do stuff with stream
}

The general rule is to dispose everything that is disposable.

In the specific case of a FileStream , you don't need to dispose it to close the file, you only need to use the Close method.

You should however dispose of the FileStream object anyway, as it has a finalizer. This will remove the object from the finalizer queue and make it a plain object that can be garbage collected in a single pass. If you don't dispose it, the garbage collector have to run the Finalizer method, and can't collect it until later, so it will linger in memory longer.

As you should dispose the object anyway, you can just put it in a using block. That will call the Dispose method, which in turn will call the Close method, so you don't need to do that yourself:

using (System.IO.FileStream stream = System.IO.File.Create(Path + file.Name)) {
  stream.Write(document, 0, document.Length);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM