Using System.Diagnostics.TraceSwitch in ASP.NET 2.0

M

Moe Sisko

According to the documentation, instance members of the TraceSwitch class
are not guaranteed to be thread safe.

Consider the following code :
==
in class "A":
public static TraceSwitch BlahSwitch = new TraceSwitch("blah",
"blah");

in class "B" :

private void DoSomething()
{
if (A.BlahSwitch.TraceError)
System.Diagnostics.Trace.WriteLine("Error occured");
==

In doing some testing, I saw cases where BlahSwitch.TraceError sometimes had
the incorrect value. (To reproduce this, I created mulitple threads in a
winform app, and accessed BlahSwitch.TraceError from different threads at
the same time).

So, I'm wondering if using static instances of TraceSwitch is a good idea in
ASP.NET ?
Otherwise, creating a local instance of the TraceSwitch everytime it is
needed seems very inefficient.
 
J

John Saunders [MVP]

"Moe Sisko" <null> wrote in message
....
So, I'm wondering if using static instances of TraceSwitch is a good idea
in ASP.NET ?
Otherwise, creating a local instance of the TraceSwitch everytime it is
needed seems very inefficient.

Any time you use a static instance of anything in ASP.NET, you need to be
cautious. It can be accessed from multiple requests at the same time, which
means multiple threads at the same time. As the documentation said, the
instance methods of those classes are not thread-safe, so your code is not
thread-safe.

I recommend you not concern yourself with the performance impact of
instantiating a TraceSwitch, until you find that there _is_ a performance
impact. For all you know, .NET could be caching the important parts of the
TraceSwitch, causing little or no performance impact to you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,229
Latest member
GloryAngul

Latest Threads

Top