Hello everyone,
Suppose I am using append mode to write to a file using StreamWriter. My application is a long run Windows service. I get the handle of StreamWriter only once during the start of my application by using StreamWriter abc = new StreamWriter (...). I never close the handle abc until application stops, and will use the handle to perform write operations in the runtime of the application.
I only write to the file rarely, for example, there may be no write operation for 2 days or something.
My question is, if I obtain the handle of the StreamWriter too long without any write operations (for example, 2 days or longer), will the handle (or the underlying file) be closed by some parties (e.g. CLR, OS, etc.) -- like timeout of socket?
thanks in advance,
George
George GeorgePosted Jun 13, 2008, 2:39 AM
Thanks Ryan,
If a open a file for a long time and no operation on it, will it be automatically closed (not by myself)?
regards,
George
Ryan AlfordPosted Jun 12, 2008, 11:38 AM
George GeorgePosted Jun 11, 2008, 9:24 PM
Thanks Ryan and Mahesh,
Generally, I agree with you. My situation is,
1. This is a file like a log file, if there are errors, I write to it, no errors, no write operation. So, this is why for a long time, if no errors or something, no write operation;
2. The file is always a local file;
3. If there are a lot of errors, there will be a lot of write operations, and fequently open/close will degrade performance?
In my situation, if no write operation for a long time, will it be closed by some parties?
regards,
George
Mahesh ChandPosted Jun 11, 2008, 1:44 PM
In good programming practices, any resources (connection, IO or printer etc) you use in your application MUST be freed as soon as you are done using them.
I always use try...catch...finally block and free my resources on finally block to make sure resources are not clocked. Here are some readings on try..catch..finally.
Alternatively, you can use the "using" statement and create new resources inside this loop. The CLR automatically closes any resources allocated within this loop as soon your loop execution is completed. Here are some readings on the "using" statement.
Ryan AlfordPosted Jun 11, 2008, 11:43 AM
George GeorgePosted Jun 11, 2008, 5:40 AM
Thanks maveric,
Let me know if you have found any documents for my question whether or not there is documented behavior whether or not the file will be closed if not used for a long time. :-)
regards,
George
mavericPosted Jun 11, 2008, 5:17 AM