swiftgp
swiftgp

Reputation: 1015

Locking an object

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

Upvotes: 1

Views: 113

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564811

Is the locking as shown below acceptable? Or should I lock the StreamWriter directl

Neither is particularly safe. It would be far more safe/secure to handle this within your class itself. Instead of exposing the StreamWriter to the outside world, make your own WriteLine method, and handle the locking internally. This makes it impossible to avoid the lock by accident.

For example, something like:

public class Logger
{
    // Make an object to use for locking
    private readonly object syncObj = new object();

    StremWriter sw;

    public Logger()
    {
        sw = new streamwriter(tempPath);
    }

    public void WriteLine(string textToOutput) 
    {
        lock(syncObj)
            sw.WriteLine(textToOutput);
    }
}

Upvotes: 5

Related Questions