Writing and appending to text files

Hi All - I’m working on a program that reads an input file, does some math, then generates an output file. This is all nested inside of a thread. I’ve coded the ability to do this on multiple inputfiles at once, i.e. multiple instantiations of the thread are created - each being given a different input file. I’d like the calculation to have one central log file that just gives the user some basic information about the progress of the calculation. I created this file before any instantiations of the thread, and added some header to the file. Then, inside each instantiation of the thread, the AppendToTextFile method is used to update the central file.

Given the current set up, the resulting “central file” contains ONLY the text added by each instantiation of the the thread, NOT the header files. If I comment out all calls to AppendToTextFile, then the header appears. Why does the program refuse to add the headers when the AppendToTextFile method is called?

I can reproduce the error. Check this out - https://docs.google.com/file/d/0B-RnBMDpi8q_VW5YNEliOU9lRWs/edit?usp=sharing - and you will see that behind the pushbutton in window1 I use TextOutputStream.Write to write to a file I create and then within a separate class (Window2) which contains a thread I use TextOutputStream = Folderitem.AppendToTextFile to update the file. If the calls to new instances of window2 are commented out, then the header printed to the text file from window1 are successful. However, if instances of window2 are called and the text file is updated then the header never prints.

Any ideas? I did just realize that I didn’t close the file I was writing to but I’m not sure this would cause the problem. I will check.

DARN! Adding the TextOutputStream.close() fixed the problem. Well I feel like a fool :-/

Probably some behind-the-scenes caching going on there. The other way to handle it is to have another thread (or timer on your main thread) handle all the writes to the log. When you need to add to the log, you would add to a queue instead, then the LogWriter would periodically check the queue, write what it finds there, then clear it.

I like that Kem. It is neater and may come in handy for some future developments. Thanks!

In fact, you can (and should) turn this into a reusable class, maybe subclassed on a Timer so you can easily adjust the period.

The situation is analogous to updating the UI from a thread. Any shared resourse - UI, file, socket - should be protected in the manner Kem suggests.