Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to keep C# Filestream open for long periods of time?

Inside my web service, I open a filestream to a file on local disk. I keep this around for the lifetime of the service. For every query that comes in, I use the filestream to read the disk. I do this to avoid having to reopen the filestream on every query. Latency of this path is critical (should less than few ms). I use SSD to keep disk IO time to 0.1ms or less.

Can the filestream 'go bad' (become invalid) over long periods of time (days). Is it safer to just reopen the filestream on every query? If I have to reopen, what's the overhead of constantly reopening a filestream several times a second?

like image 220
user201511 Avatar asked Nov 07 '12 19:11

user201511


1 Answers

The only concern I would have leaving the file open is if the application were to fail, for whatever reason, and could not recover from its current location to close the stream; the CreateFile entry point in KERNEL32 which is used to open the file makes the following statement:

When an application is finished using the object handle returned by CreateFile, use the CloseHandle function to close the handle. This not only frees up system resources, but can have wider influence on things like sharing the file or device and committing data to disk. Specifics are noted within this topic as appropriate.

So I would think it's much more appropriate to open and close the FileStream every single time.

like image 85
Mike Perrenoud Avatar answered Sep 19 '22 20:09

Mike Perrenoud