Subj : Re: [.NET] Lock Object To : comp.programming.threads From : David Hopwood Date : Sat Sep 24 2005 04:48 pm Cool Guy wrote: >>Actually I should've mentioned that I had a Singleton with lazy >>instantiation in mind when I wrote that. > > Here's the code: > > sealed class LogFile > { > #region Singleton functionality > public static readonly LogFile Instance = new LogFile(); > > static LogFile() { > } > #endregion > > StreamWriter streamWriter; > readonly object streamWriterLock; > > LogFile() { > streamWriterLock = new Object(); > FileStream fileStream = File.Open(...); > lock (streamWriterLock) { // lock for write memory barrier > // (not sure whether this is needed) > streamWriter = new StreamWriter(fileStream, Encoding.ASCII); > } > } > > public void AddEntry(string text) { > lock (streamWriterLock) { > streamWriter.WriteLine(text); > streamWriter.Flush(); > } > } > } No problem as long as you only ever access streamWriter within the lock. Accessing it outside the lock won't work. -- David Hopwood .