Each TraceListener in the System.Diagnostics namespace (.NET 4) has IsThreadSafe property. The .NET Tracing infrastructure decides to use a lock to synchornize multiple calls to the TraceListener’s Trace methods based on this property.
What is the need for the DefaultTraceListener to be marked by as not ThreadSafe by the BCL team? It appears (from Reflector) that the core logic for the listener is this:
private void internalWrite(string message)
{
if (Debugger.IsLogging())
{
Debugger.Log(0, null, message);
}
else if (message == null)
{
SafeNativeMethods.OutputDebugString(string.Empty);
}
else
{
SafeNativeMethods.OutputDebugString(message);
}
}
Does access to the Debugger.Log method or the OutputDebugString string needs to be synchronized?
References:
In addition to writing to the
OutputDebugString, theDefaultTraceListeneralso writes to log file if one is specified. It does not do any locking to access the file, and so, it is not marked thread-safe. It relies on the tracing infrastructure to serialize access to it’s methods.We can specify the log file-name as follows: