I have simplified this code for example purposes:
class TextLogger : IDisposable
{
private FileStream m_FileStream;
private StreamWriter m_StreamWriter;
void CreateNewLogFile()
{
//Open the File
m_FileStream = File.Open(
m_CurrentFileName,
FileMode.OpenOrCreate,
FileAccess.Write,
FileShare.Read );
m_StreamWriter = new StreamWriter( m_FileStream );
....
}
}
I get an InvalidArgumentException when trying to new up the StreamWriter, because m_FileStream has already been disposed by another thread and is null (m_StreamWriter is also null). How do I put a lock around the member variable?
You should do something like this
When
CalledFromOtherThreadis called from another thread it should acquire the lock and then dispose the m_FileStream. This way inCreateNewLogFileyou will never have a disposed FileStream