I myself created a thread safe logging class. I used it something like this.
Logging obj = new Logging(filename); Action<string> log = obj.RequestLog();
RequestLog will return an anonymous method that wrote in turn. Since Q is thread safe for 1 reader / writer, I did not need to use any locks when calling the log ()
The actual logging object will create a new thread that will run in the background and periodically check all queues. If Q had a string, it would write it to the buffer stream.
I added a little extra code to the read stream, so for each pass that he made in the queues, if nothing was written, he will sleep an additional 10 ms, up to a maximum of 100 ms. Thus, the thread was not too wet. But if heavy writing would occur, he would interview Qs every 10 meters.
Here is the snpit return code for the requested queue. "This.blNewData = true" was such that I did not need to check every Q to see if any new data was recorded. No blocking is associated because the false positive still did not work, since all Qs would still be empty.
OutputQueue was a list of queues that I looped to find out if anything was written. The code to scroll through the list was blocked when NewQueueLog () was called and caused the list to resize.
public Action<String> NewQueueLog() { Queue<String> tmpQueue = new Queue<String>(32); lock (OutputQueue) { OutputQueue.Add(tmpQueue); } return (String Output) => { tmpQueue.Enqueue(Output); this.blNewData = true; }; }
In the end, logging was blocked, which helped when many threads were written.
source share