I am writing a multi threaded application and I am also trying to work out how to write suitable unit tests for it. I think that’s probably another question on how best to do that.
One more question, I have a class like the below knowing its not thread safe and want to prove it in a unit test but cannot work out how to do it:
public class MyClass
{
private List<string> MyList = new List<string>();
public void Add(string Data)
{
MyList.Add(Data); //This is not thread safe!!
}
}
Proving that something is thread safe is tricky – probably halting-problem hard. You can show that a race condition is easy to produce, or that it is hard to produce. But not producing a race condition doesn’t mean it isn’t there.
But: my usual approach here (if I have reason to think a bit of code that should be thread-safe, isn’t) is to spin up a lot of threads waiting behind a single ManualResetEvent. The last thread to get to the gate (using interlocked to count) is responsible for opening the gate so that all the threads hit the system at the same time (and already exist). Then they do the work and check for sane exit conditions. Then I repeat this process a large number of times. This is usually sufficient to reproduce a suspected thread-race, and show that it moves from “obviously broken” to “not broken in an obvious way” (which is crucially different to “not broken”).
Also note: most code does not have to be thread-safe.