views:

277

answers:

2

msdn: "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe." it contains only instance methods.

How should I use it in a way that all activity gets recorder by TextWriterTraceListener to a text file. Is one static member which all threads use (by calling) TraceEvent-method safe.

(I've kind of asked this question in http://stackoverflow.com/questions/1901086/how-to-instantiate-c-tracesources-to-log-multithreaded-asp-net-2-0-web-applica, but I cannot just believe if somebody just says it's OK despite the documentation).

A: 

When using a resource that isn't thread safe (or isn't guaranteed to be thread safe) in a multi-threaded app I'll use the lock keyword

lock( _lockObject)
{
  // do my non-thread-safe-operations here
}

Documentation/examples for the lock keyword can be found here:

http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.71).aspx

As for all threads using a common static instance of the class - that isn't necessarily thread safe. Using a static instance ensures that the state of the object is shared/consistent among the threads but desn't necessarily prevent parallel calls to the method. In fact, if the instance methods are making use of some common state variables within the static object - accessing the object from multiple threads could introduce additional problems - race conditions, multiple threads attempting to access the same resource, etc. A static instance of an object does not prevent these conditions.

If you are using a static instance of the object, put a lock around it when you are operating on it and you should be okay.

James Conigliaro
yes or monitor class. but mys question is: is it safe to have one static instance of TraceSource and use it's TraceEnvent-method? see http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/93696038-2255-4d7c-a53a-b0b1bcdd2fc2.
matti
I see. I further elaborated on my answer. Hope it helps.
James Conigliaro
in case of TraceSource the 'thread-unsafeness' may be because the TraceListener is not thread safe. That's why there is TraceInternal.UseGlobalLock. What I want to know is: If TraceListener.IsThreadSafe return false like TextWriterTraceListener's is this global lock enough? I don't want to make double locking for performance reasons. see for example http://www.grimes.demon.co.uk/workshops/InstrWSThree.htm
matti
+1  A: 

The TraceSource class is thread safe. See http://msdn.microsoft.com/en-us/library/system.diagnostics.tracesource.aspx.

I believe that previously it wasn't listed as thread safe but that was a documentation bug.

hwiechers