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

maveric8 reputationPosted Jun 11, 2008, 1:17 AM EDT
George GeorgeRank #1,736 · 870 reputationPosted Jun 11, 2008, 1:40 AM EDT
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
Ryan AlfordRank #1,411 · 1.2K reputationPosted Jun 11, 2008, 7:43 AM EDT
Mahesh ChandRank #1 · 393.4K reputationPosted Jun 11, 2008, 9:44 AM EDT
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.
George GeorgeRank #1,736 · 870 reputationPosted Jun 11, 2008, 5:24 PM EDT
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
Ryan AlfordRank #1,411 · 1.2K reputationPosted Jun 12, 2008, 7:38 AM EDT
George GeorgeRank #1,736 · 870 reputationPosted Jun 12, 2008, 10:39 PM EDT
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