使用“使用” C# 中使用 StreamWriter 的语句
我的应用程序有一个记录器,它不断地将数据记录在许多不同的文件中。每个文件的登录是使用“using”块内的 StreamWriter 对象同步完成的。有时,我会收到一个异常,说我尝试打开的文件正在被另一个进程使用。
现在,我登录的每个文件都有一个与客户端 ID 关联的唯一名称。我的应用程序是多线程的,但在任何时候只有 1 个客户端实例处于活动状态,因此我确信同一个文件不会被超过 1 个线程打开。但是,我的应用程序确实在不到 1 秒的时间内多次登录同一个文件,每次日志都尝试重新打开该文件。这让我得出另一个结论,即“using”语句不会立即关闭文件(即使我读过它对文件确实如此),而只是将其释放并等待 GC 处理关闭。
我的结论是正确的还是其他原因导致了异常?
My application has a logger which constantly logs data in a number of different files. Logging in each file is done synchronously using a StreamWriter object inside a "using" block. From time to time, I get an exception saying the file I'm trying to open is being used by another process.
Now the files I log into each has a unique name associated with the client id. My application is multi-threaded, but at any point in time only 1 instance of the client is active, so I am sure that the same file is not opened by more than 1 thread. However, my application does logs in the same file multiple times in say less than 1 second, for each log attempting to reopen the file. This leaves me to one other conclusion, that the "using" statement does not immediately close the file (even though I've read that it does for files), but only disposes it and waits for the GC to handle the closing.
Is my conclusion correct or is it something else that's causing the exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
退出
using
语句后,不仅会调用Close
,还会调用Dispose
,因为using
没有任何作用else then 语法糖 for所以问题出在多线程访问中,它以某种方式尝试访问 writer 尚未处理的文件,这并不意味着
using
语句不起作用,而是意味着它仍然有完成它的工作。编辑
您可以尝试使用ProcessExplorer来检查指定文件句柄所有权。查看在线帮助了解如何操作。
After exiting the
using
statement not only call toClose
is made, but also toDispose
, causeusing
is nothing else then syntax sugare forSo the problem is in multithreaded access, that somehow tries to access a file whom writer not yet disposed, which does not mean that
using
statement does not work, but means that it still has to finish it job.EDIT
You can try to use ProcessExplorer to check the specified file handle ownership. Check out online help for how to do it.
你的结论是不正确的。使用 Close 或 Dispose 关闭文件(或退出 using 块)后,您可以立即在另一个 using 块中重新打开该文件。
必须有其他线程使用该文件。
Your conclusion is incorrect. Once closed with Close or Dispose (or exiting a using block), you can then immediately reopen the file in another using block.
There has to be some other thread using the file.
using 语句将调用 FileStream 上的 Dispose,这将立即释放底层文件句柄。您的问题是由于文件写入重叠造成的。
The using statement will call the Dispose on the FileStream which will immediately release the underlying file handle. Your issue is due to overlapping in file writes.