Nice. In answer to your questions, your class is not thread-safe, but it could be with a few minor changes. By default, the StreamWriter class is not thread-safe so your Write() and WriteLine() methods are not thread-safe. Unfortunately, the StreamWriter class does not expose a Synchronized property, so the easiest thing to do is to declare a member variable called padlock that is just an object, i.e.
private object _padLock = new object();
In your adjust your write() method to look like:
public override void Write(string value)
{
lock(_padLock)
{
checkRollover();
_traceWriter.Write(value);
}
}
Do the same for your WriteLine() method.
Your CheckRollover method is also not thread-safe, however, if you implement the above locking in your write methods and if its true that only the write methods call CheckRollover(), then nothing else needs to be done. Nevertheless, I would re-write CheckRollover() to look like the below. This way, anything can could call CheckRollover() in the future. If there were a synchrnoized wrapper in the StreamWriter class and you were to use it instead of locking, then CheckRollover would cause a race condition without the locking below.
private void checkRollover()
{
// If the date has changed, close the current stream and create a new file
if (_currentDate.CompareTo(System.DateTime.Today) != 0)
{
lock(_padlock)
{
if (_currentDate.CompareTo(System.DateTime.Today) != 0)_
{
_traceWriter.Close();
_traceWriter = new StreamWriter(generateFilename(), true);
}
}
}
}
Note that in .Net its okay to have nested locks on the same object (i.e., WriteLine locks padlock and then calls checkRollover, which also locks on _padlock, but it won't be blocked.
Anyway, I am going to use this. Thanks.