Reputation: 34036
I am looking for a way to log to file without blocking the calling thread. still all log-calls must be executed in order.
i was thinking of something like
void Log(string msg)
{
ThreadStart ts = new ThreadStart ()
{
System.IO.File.AppendAllText("log.txt", msg);
};
new Thread(ts).Start();
}
but will this guarantee to log everything in in order?
also the Log method should be calleable from any thread at any time.
Upvotes: 0
Views: 983
Reputation: 15091
If you aren't doing this for the sake of learning; you might want to consider utilizing existing logging frameworks. There are lots of potential 'gotchas' when rolling your own and (in most cases) the logging you want has already been written.
I haven't used them all, but I can say I've never been in a situation where log4net didn't already do what I needed (and better than I would have written).
https://stackoverflow.com/questions/126540/what-is-your-net-logging-framework-of-choice
Upvotes: 0
Reputation: 1187
Us this:
http://msdn.microsoft.com/en-us/library/dd267265.aspx
Then push on to the queue in order. Have the thread pull from the Concurrent queue. This will preserve your order.
When you log don't start a new thread for each log. Only have one "logging" thread.
Upvotes: 2
Reputation: 30728
but will this guarantee to log everything in in order?
This will log in random order. Sometime will also create Access Denied issue
due to concurrent writes to same file.
Better way is to keep internal buffer of logs, and write out in separate single thread in a timer. This will make loss of in-memory logs(not written to file) in case of app crash.
Upvotes: 2