Robert Robert - 3 months ago 33
C# Question

Simple MultiThread Safe Log Class

What is the best approach to creating a simple multithread safe logging class? Is something like this sufficient? How would I purge the log when it's initially created?

public class Logging
{
public Logging()
{
}

public void WriteToLog(string message)
{
object locker = new object();

lock(locker)
{
StreamWriter SW;
SW=File.AppendText("Data\\Log.txt");
SW.WriteLine(message);
SW.Close();
}
}
}

public partial class MainWindow : Window
{
public static MainWindow Instance { get; private set; }
public Logging Log { get; set; }

public MainWindow()
{
Instance = this;
Log = new Logging();
}
}

Answer

No, you're creating a new lock object every time the method is called. If you want to ensure that only one thread at a time can execute the code in that function, then move locker out of the function, either to an instance or a static member. If this class is instantiated every time an entry is to be written, then locker should probably be static.

public class Logging
{
    public Logging()
    {
    }

    private static readonly object locker = new object();

    public void WriteToLog(string message)
    {
        lock(locker)
        {
            StreamWriter SW;
            SW=File.AppendText("Data\\Log.txt");
            SW.WriteLine(message);
            SW.Close();
        }
    }
}
Comments