I have a web application, that will log some information to a file. I am looking for a simple thread-safe non-blocking file logger class in c#. I have little experience with threading. I known there are great logging components out there like log4Net, Enterprise Library Logging Block, ELMAH, but I do not want an external dependence for my application. I was thinking about using this queue implementation http://www.codeproject.com/KB/cpp/lockfreeq.aspx
The FileStream.BeginWrite method pushes the write operation onto a thread that's managed by the system. That's the easy bit.
If you put your messages into a synchronized Queue, and have the EndWrite method pull the next item off the queue, then all your logging will be off-thread as far as the app is concerned.
The last step is to wrap putting messages onto the queue to set an event, so that if the queue is empty when EndWrite comes to look for the next message, it can wait for the event to be set.
if you do not want to use external library, you can use Trace class
I've done a simple logging mechanism in my project in the office.
I have a log class that is Shared (Static C#).
Inside this class I have a Synchronised Queue, and it has it's own thread.
Then inside this thread, I just have it use a AutoresetEvent with your own defined WaitTime (i use 250ms).
Then when this ResetEvent times out, I collect what is currently in the queue (using DeQueue) and write each on to the File.
Things to remember ... Have a class or struct that can hold the date when the Entry went in, rather than the time you wrote to disk, incase you choose a longer time to sleep your thread.
If you want your application to exit quickly expose a method that will Set the Event to drop it out of the sleep and exit gracefully.
Take a look at this; it's simple, yet thread-safe and non-blocking.