C# TraceSource class in multithreaded application
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 how to instantiate C# TraceSources to log (multithreaded) ASP.NET 2.0 Web application (asmx ws)?, but I cannot just believe if somebody just says it's OK despite the documen开发者_如何学Pythontation).
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.
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.
精彩评论