Peter
Peter

Reputation: 2263

Writing from multiple threads to one file in .net 4.0

I got a scenario where an old huge console program misbehaves, someone wrote it in .net 4.0 and left company. Due to multi-threading its kinda hard to debug, the workflow of the application is also questionable and without comments on code its a hard to figure out what actually happens when, and on which thread.

So the idea rose to create multi-threading aware logging hook.
So one file log can dump info about all those threads wherever we like.

I wrote something that seams to do it, though i'm not sure if this code should be used in .net 4.0 (lock does hold the tasks for this file write, i believe).. but not sure maybe there should be a queue or so, so that multiple threads add their text and the logwriter, writes and dequeues it.

On the other hand, maybe this is allready enough and then i'm adding to much complexity, my biggest worries is that somehow the code could get into freeze because of the Lock(locker).

public static class LogWriter
    {
        private static object locker = new Object();

        public static void Write ( string Filepath,string text )
        {
            lock (locker)
            {
                using (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write, FileShare.Read))
                using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode))
                {
                    writer.WriteLine(text);
                }
            }
        }
    }

Upvotes: 1

Views: 701

Answers (1)

Frederik Carlier
Frederik Carlier

Reputation: 4776

In general, I think you can assume your code will work. If multiple threads call Write at the same time, your lock will effectively cause them to append text to the file one at a time.

There are a couple of things that come to mind when looking at your code:

  • Every call to Write will create a new FileStream and StreamWriter and dispose of it at the end. That sounds very expensive, and it may be better to keep file and writer in static variables and close them at the end
  • Your calls to logging will be synchronous, so any thread which logs, will block until the logging is complete. You may want to do this asynchronously.

Generally speaking, though, I think your best option is to look at some of the existing logging frameworks and see if you can use them. You don't need to write your own "create multi-threading aware logging hook", others have done so before you.

Some good logging frameworks are NLog, Serilog, log4net, ELMAH,... I think your best bet is to use any of these logging frameworks.

Upvotes: 1

Related Questions