Hi,
An application needs a counter, which value to be stored in a text file. Sometimes it happens on very short intervals.
This test code rewrites a text file very often (f.e. every 100 milliseconds):
int counter = 0;
while (true) {
WriteToFile(counter);
counter++;
Thread.Sleep(100);
}
private void WriteToFile(int counter) {
byte[] buffer = Encoding.ASCII.GetBytes(counter.ToString());
using (FileStream createFile = new FileStream("Counter.txt", FileMode.Create))
{
createFile.Write(buffer, 0, buffer.Length);
createFile.Close();
}
}
It works basically fine except in one of our "reliable tests" - stopping the computer electricity supply while the application is running. The bad surprise was - in the file wasn't any text (should be a number) but only one or two space characters. The missing last value it tries to write is understandable but making the file not consistent is really bad...
Trying the use of:
createFile.Flush(); createFile.Close(); createFile.Dispose();
GC.Collect(); GC.WaitForPendingFinalizers();
doesn't help.
Any help will be appreciated.