I've written the piece of code below for an integration test which calls an expensive function DoSomething() for several different assemblies. I would have thought applying a lock would be enough to ensure thread safety but sometimes the boolean value is true when it should always be false in my current test case.
I've also tried the solution here with the Interlocked.CompareExchange which doesn't seem to work for me as well.
Can someone please point me in the right direction as to what exactly I'm doing wrong?
public class SomeClass
{
private object _lock = new object();
private volatile bool _isSuccessful = true;
private bool IsSuccesful
{
get
{
lock (_lock)
{
return _isSuccessful;
}
}
set
{
lock (_lock)
{
_isSuccessful = value;
}
}
}
public bool Get()
{
Parallel.ForEach(..., ... =>
{
IsSuccesful = IsSuccesful & DoSomething();
});
return IsSuccesful;
}
}