Possible Duplicate:
Unit test for thread safe-ness?
I'm looking for best way to unit test if some code is thread safe.
I'm using NUnit and Moq as unit test framework.
Well, does your code use concurrency? Because if it doesn't it already thread-safe. I believe your question is fundamentally wrong and should have been something along the line of "How do I design thread safe code?"
The problem with such a question is that it's very broad and there are a plethora of things to consider when designing code to be thread-safe.
However, something you can do to test your code, is to use brute force and multiple threads over an extended period of time. If the results are inconsistent, then there could be a synchronization problem. The issue here is of course that the inconsistent results doesn't have to be a concurrency related issue, it could still have happen using a single thread.
What you need to do is to look at the code that you expect to be thread-safe and basically ask yourself "What happens if I sleep for an indefinite amount of time here?". If you conclude that everything works while running the concurrent code with a lot of random sleep durations interleaved (this makes concurrency issues more apparent) then you're on the right track.
精彩评论