views:

326

answers:

1

None of the examples on TraceSource I found addresses multithreading. I create new instance of a class (SyncService) to serve a incoming request. When there is lots of activity there is multiple threads that need to use this TraceSource to log activities. How should I use this class for logging with performance and thread safety in mind? I have some opts in mind:

    private static TraceSource _source;

    static SyncService()
    {
        _source = new TraceSource("mySrc");
    }

in case above the thread safety is an issue. There is quite a lot logging so i don't want to make locks everywhere to guard access to TraceEvent-method. What about removing both static-keywords? Is there lots of overhead when all the requests do logging from their own TraceSource? Is there better solution than these 2? msdn states: "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe." What should i thinks about that?

+1  A: 

Define TraceSource like this to ensure you only get one instance:

private static readonly TraceSource _source = new TraceSource("mySrc");

This will make sure it is created before any thread starts using it, so you are guaranteed one instance only.

TraceSource has default a global lock in Trace.UseGlobalLock. This will automatically lock for you around all trace listeners. If set to false it will lock per TraceListener if the listener is not defined as thread safe instead.

Tracing can be a bottle neck if the recording speed is "slow" and the volume of tracing is large.

To ensure max speed you need to use as few trace listeners as possible, make sure they are thread safe, and set Trace.UseGlobalLock = false. If you don't have control over listeners being added in your app.config you should keep the global lock.

Mikael Svenson
thanks! i'm planning to use only TextWriterTraceListener. it is not thread safe. i dont' understand why listeners have to be synchronized. in http://msdn.microsoft.com/en-us/library/ms228993.aspx u just add listeners and they appear as passive (no methods are called), all the action is in TraceSource. why we don't need to control access to it? i.e. when calling _source.TraceEvent from multiple threads. msdn clearly states that it is not thread safe.
matti
If you look at the implementaion of TraceEvent in for example Reflector it clearly has locking implemented. But if a TraceListener says it's thradsafe, but in reality is not, then the claim "not guaranteed to be thread safe" is correct.
Mikael Svenson
If you accept my answer, please mark it.
Mikael Svenson