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();
}
}
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
lockerout of the function, either to an instance or a static member. If this class is instantiated every time an entry is to be written, thenlockershould probably be static.