I’m having a real strange issue while working with streams in mono.
I open a stream like this:
_stream = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
Where _stream of course is a FileStream. I added a dispose method for this class like that:
public override void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if(!_disposed)
{
if(disposing)
{
_stream.Flush(true);
_stream.Dispose();
_items.Clear();
}
_disposed = true;
}
}
Now i have this simple test:
[Test]
public void SimpleTest()
{
SyncFileWriter s = new SyncFileWriter("file");
s.Save("a", "b");
s.Dispose();
SyncFileWriter s2 = new SyncFileWriter("file");
s2.Dispose();
}
But if fails with a IOException: Sharing violation. [edit]It looks like there was an error with monodevelop. Restarted it and now it fails everytime[/edit]
How to avoid this and close the stream properly?
It looks like it was my fault. The SyncFileWriter is derived from a abstract class that checkes whether the file exist, or not. If not, it will initialize this file with some default things and that’s why I did the following
As you see, I create a file, but File.Create opens a stream and does not close it after leaving it’s scope, whatever.
Now I do this:
and everything is fine.
I think here lies also the problem for the first nondeterministic behavoir, because it does this only, when a parameter is null, and it is only null, when you create a new file.
Anyway, Thanks for your help!