Domanda

I have a C# program that uses a simple logging class to (you guessed it) create log files. The code I have for the class constructor is below. I'm wondering if since its only using a single thread, do I really need to use lock on the stream?

public Logger(MemoryStream stream)
    : base(stream)
{

    try
    {
        // Flush the buffers automatically
        this.AutoFlush = true;

        lock (this.BaseStream) // <-- Do I need this?
        {
            // Writes header to log file
            this.WriteLine("Date & Time: " + DateTime.Now.ToString());
            this.WriteLine("OS: " + OSVersion.GetOSVersion());
            this.WriteLine();
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex);
    }
}

UPDATE: Sorry to take this question off course, but I just found out that it does use multiple threads. My next question is, with a lock on this.BaseStream, can it be accessed to use WriteTo to copy it to another stream like so:

lock (this.BaseStream)
{
    using (FileStream fileStream = new FileStream(strNewFileName, FileMode.Create, FileAccess.Write))
    {
        (this.BaseStream as MemoryStream).WriteTo(fileStream);
    }
}
È stato utile?

Soluzione

You should not lock the object you are about to use, create a lock object that you can use for that instead.

private readonly object myLock = new object();

void DoThreadedStuff(){
  lock(myLock){
    //Anything that requires a lock here.
  }
}

This will only lock the myLock object, not the stream itself.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top