I'm using the FileStream and StreamReader classes like so:
using(FileStream stream = File.Open(filePath,FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
using(var reader = new StreamReader(stream))
{
content = reader.ReadToEnd();
}
}
This means I'm disposing both of them.
However, by running another app, I'm finding that there's some kind of locking remaining one some of the file I'm reading.
As well as Dispose should I be calling Finalize or Close too?
cheers!
UPDATE - Why do I think there's a Lock going on:
I have a service which writes to a some log files.
The above code is from a different WCF application which reads the logs.
I also have an automated deploy project which stops the main service, backs up the files, and adds the new version of the service, and starts it again.
if the WCF service is running (which contains the above code) I get IO exceptions while running the deploy application even though the main service has already stopped (the service which writes to the logs).
When the WCF service is not running, I get no IO exceptions and I can safely move files开发者_如何学Go around.
The only IO the WCF does is above...so I'm assuming it's keeping some kind of lock somewhere..?
No there is no need to call close on the stream mainly because the dispose method on the reader is going to do that explicitly anyway
A quick look at the code in reflector reveals this
...
if ((this.Closable && disposing) && (this.stream != null))
{
this.stream.Close();
}
...
therefore when dispose(true) is called on the Reader the underlying stream is closed and then when the using blocks exit all objects are ready for garbage collection.
The using statements are enough to free resources and is why the IDisposable pattern exists :)
It is disposing like gangbusters. The StreamReader.Dispose() will already dispose the file stream, FileStream.Dispose() will shrug and not complain.
If there is any notable problem then it is File.OpenRead(). You didn't specify a FileShare value, it will use FileShare.Read. Which is pretty normal but that will fail when somebody else has the file opened for writing. You cannot omit FileShare.Write when somebody else already has acquired the right to write. The SysInternals' Handle utility can be helpful to diagnose problems like this.
精彩评论