FileStream.Dispose 是否立即关闭文件? [英] Does FileStream.Dispose close the file immediately?

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

问题描述

我有一些代码通过使用 MemoryStream.WriteTo() 将 MemoryStream 保存到 FileStream 来写入文件.文件关闭后,它会再次打开以读取一些元数据...

I have some code that writes a file by saving a MemoryStream to a FileStream using MemoryStream.WriteTo(). After the file is closed it is opened up again to read some metdata...

这在大约 80% 到 90% 的情况下都有效.另外 20% 我收到一个异常,说该文件正在被另一个进程使用".

This works about 80 - 90% of the time. The other 20% I get an exception saying the file is "in use by another process".

FileStream.Dispose() 不是同步释放资源吗?在我不知道的 Win32 领域有什么事情发生了吗?我在 .Net 文档中没有看到任何明显的内容.

Does FileStream.Dispose() not release resources synchronously? Is there something going on lower in Win32 land I'm not aware of? I'm not seeing anything obvious in the .Net documentation.

推荐答案

尽可能立即".由于未完成的写入、更新目录信息的延迟等,很容易出现一些延迟.也可能是防病毒软件正在检查您更改的文件.

As "immediately" as possible. There can easily be some lag due to outstanding writes, delay in updating the directory info etc. It could also be anti-virus software checking your changed file.

这可能是调用 Thread.Sleep(1) 的罕见情况.但是为了完全安全,您必须捕获(任何)异常并重试一定次数.

This may be a rare case where a Thread.Sleep(1) is called for. But to be totally safe you will have to catch the (any) exception and try again a set number of times.

这篇关于FileStream.Dispose 是否立即关闭文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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