Does FileStream.Dispose close the file immediately?
Asked Answered
E

1

9

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

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

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.

Eustashe answered 14/6, 2011 at 21:10 Comment(2)
Is this on NTFS? Is the file local or on a remote share? I doubt that it is Dipose() not closing the HANDLE, I think you might be experiencing what the SAMBA developers called Window's "onerous open modes" (especially if a retry of 500-1000ms on the second open succeeds).Stickney
It's NTFS. If I keep clicking the save button on my window, eventually it saves. I'm handling errors so at least it doesn't crash.Eustashe
P
7

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.

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.

Parabolic answered 14/6, 2011 at 21:14 Comment(5)
I thought about inserting a sleep. It's not something I like to do, but, eh, sometimes that's the best solution. I might be able to overload some methods and just pass in a stream instead of a file path. That way I don't have to close then open again... Oh, and my laptop has BitLocker and anti-virus. Both make my life oh so pleasant.Eustashe
Yes, Sleep() doesn't feel right. especially when @Stickney is right with 500-1000ms retrie delays. Keeping the Stream open would be faster all way round. Or get the data from the memoryStream?Parabolic
I saw something similar today and it was down to the virus scannerSainfoin
Yesterday I disabled my virus scanner an tested for 20 minutes or so. Couldn't reproduce it. So, as far as I can tell, that's what is causing the problem. Going to look at it once more today.Eustashe
After refactoring some code I was able to move to a single file save/close operation. The problem has gone away. To the best of my knowledge, the source of this problem was the anti-virus.Eustashe

© 2022 - 2024 — McMap. All rights reserved.