我是否需要处置FileStream对象? [英] Do I need to dispose the FileStream object?

查看:49
本文介绍了我是否需要处置FileStream对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程知识非常沮丧,但是我们真的需要处理FileStream对象吗?



我问的原因是因为代码抛出了文件正在被使用另一个过程异常,在100种情况下,一次,好像我再试一次(使用文件流下载文件),它工作正常。



请参阅此代码问题



自它仅每100个发生一次,这让我非常困惑,并且它在生产服务器上发生,因此根本无法调试,但是可以在我的开发机器上完美地运行...

解决方案

一般规则是处理所有可抛弃的东西。



FileStream的特定情况下,您无需处置它即可关闭文件,只需使用 Close 方法。



但是您应该处置 F ileStream 对象,因为它有一个终结器。这将从终结器队列中删除该对象,并使其成为一个普通对象,可在一次通过中对其进行垃圾回收。如果不进行处理,则垃圾收集器必须运行 Finalizer 方法,并且要等到以后才能收集,因此它在内存中的停留时间会更长。 p>

无论如何都要处置对象,只需将其放在 using 块中即可。这将调用 Dispose 方法,而该方法又将调用 Close 方法,因此您无需执行此操作那你自己:

 使用(System.IO.FileStream流= System.IO.File.Create(路径+ file.Name) ){
stream.Write(document,0,document.Length);
}


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...

解决方案

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);
}

这篇关于我是否需要处置FileStream对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆