Does TraceSource.Trace methods block the calling thread until it is processed by all listeners?

578 Views Asked by At

I am new to .net tracing.

I have nearly more than 10 to 15 trace sources in my application and a text file listener and sql server listener in shared listeners list. My question is if I call

 traceSource.TraceInformation("Sample information")

then the calling thread will be blocked till it is processed/traced by text file listener and sql server listener. Or TraceSource internally contains any queue for logging, so that the calling thread will be released immediately and logging will be done in the background thread.

Basically I dont want the calling thread to be blocked until it is logged by all the trace listeners. If I want to implement like that, then should I go for custom listeners?

1

There are 1 best solutions below

0
On

Your tracing is only as multithread safe as your listeners. If many threads are trying to write to the same file via trace, there can be some contention, some listeners will write to another log file if the current one is already open. I know from experience writing to the console trace listener that sometimes the text will interleave as two threads try to write to the console at the same time. That implies to me that nothing in the System.Diagnostics framework code is going to force blocking.

To test a slow listener blocks, you can determine that empirically by implementing a custom listner, I recommend this base class so you really only need to override at most two methods to write a custom listener. Add a Thread.Sleep(6000) and see if all threads block.

If they do, you might want to consider putting your trace calls into some sort of fire-and-forget invocation, maybe Task.Run, Task.StartNew or new Thread/Start. However, I suspect the overhead of creating a new thread will possibly make performance worse than blocking for a few milliseconds. Here is one related question.