开发者

how to instantiate C# TraceSources to log (multithreaded) ASP.NET 2.0 Web application (asmx ws)?

开发者 https://www.devze.com 2022-12-13 19:59 出处:网络
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 threa

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消