I have a class structure as below
public class Logger
{
StremWriter sw;
public Logger()
{
sw = new streamwriter(tempPath);
}
public StreamWriter StreamLog
{
get { return sw; }
}
}
i am wondering how to properly lock if I try and access the StreamWriter object from two different threads. Is the locking as shown below acceptable? Or should I lock the StreamWriter directly
//Log is an instance of Logger that could be accessed from multiple threads
lock (Log) {
Log.StreamLog.WriteLine("temp");
}
Edit: These log objects would be going in a ConcurrentQueue from where different threads could retrieve them
Neither is particularly safe. It would be far more safe/secure to handle this within your class itself. Instead of exposing the
StreamWriterto the outside world, make your ownWriteLinemethod, and handle the locking internally. This makes it impossible to avoid the lock by accident.For example, something like: