Is there any standard, recommendation or guidelines for thread-safety
programming?
The most important standard is to ensure that all static members are thread-safe. You will see that all well written APIs including the .NET base class library makes this guarantee across the board. There is a really good reason for this. Since static members are shared across an AppDomain they could be used by many different threads without you even realizing it. It would be awkward at best to provide your own synchronization for every single static member access. Imagine what it would be like if Console.WriteLine
were not thread-safe.
As far as recommendations and guidelines there are plenty of well established patterns for doing concurrent programming. The patterns that are out there cover a wide variety of programming problems and use many different synchronization mechanisms. The producer-consumer pattern is one of many well known patterns which happens to solve a large percentage of concurrent programming problems.
Read Threading in C# by Joseph Albahari. It is one of the best and most vetted resources available.
When I use lock(C#) keyword, it means my class is thread-safe or not?
Nope! There is no magic bullet that can make a class thread-safe. The lock
keyword is but one of many different tools that can be used to make a class safe for simultaneous access by multiple threads. But, just using a lock
will not guarantee anything. It is the correct use of synchronization mechanisms that makes code thread-safe. There are plenty ways to use these mechanisms incorrectly.
How to I evaluate thread-safety of a class? Is there any TESTS to be
sure that a class is 100% thread safe?
This is the million dollar question! It is incredibly difficult to test multithreaded code. The CHESS tool provided by Microsoft Research is one attempt at making life easier for concurrent programmers.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…