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?>
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();
}
}
}