So I have a static class that is supposed to be used as a log file manager, capable of adding “messages” (strings) to a Queue object, and that will push messages out to a file. Trouble is, many different threads should be enqueueing, and that the writer needs to be async as well. Currently when I insert into the queue, I’m also checking to see if the writer is writing (bool check), if it’s not, i set the bool and then start the writing, but I’m getting intermittent IO exceptions about file access, and then wierd writing behavior sometimes.
Someone want to give me a hand on this?
It sounds like the queue is driving the file writing operation. I recommend that you invert the control relationship so that the writer drives the process and checks the queue for work instead.
The simplest way to implement this is to add a polling mechanism to the writer in which it checks the queue for work at regular intervals.
Alternately, you could create an observerable queue class that notifies subscribers (the writer) whenever the queue transitions from empty: the subscribing writer could then begin its work. (At this time, the writer should also unsubscribe from the queue’s broadcast, or otherwise change the way it reacts to the queue’s alerts.)
After completing its job, the writer then checks the queue for more work. If there’s no more work to do, it goes to sleep and resume polling or goes to sleep and resubscribes to the queue’s alerts.
As Irwin noted in his answer, you also need to use the thread-safe wrapper provided by the
Queueclass’Synchronizedmethod or manually synchronize access to yourQueueif multiple threads are reading from it and writing to it (as in SpaceghostAli’s example).