Why does the Debug.Assert statement sometimes fail?
I write the below code, but sometimes Debug.Assert raise fail. Why does the Debug.Assert statement sometimes fail and how can I fix it?
public class Warehouse
{
pri开发者_开发百科vate int stockCount = 0;
public void DecrementStock ()
{
if ( stockCount > 0 )
stockCount--;
Debug.Assert ( stockCount >= 0 )
}
public void IncrementStock()
{
stockCount ++;
}
}
This really smells like a multi-threading issue. I suggest placing a lock
around access to the stockCount
member.
public class Warehouse
{
private int stockCount = 0;
private object stockSynch = new object();
public void DecrementStock ()
{
lock(stockSynch)
{
if ( stockCount > 0 )
stockCount--;
Debug.Assert ( stockCount >= 0 )
}
}
public void IncrementStock()
{
lock(stockSynch)
{
stockCount ++;
}
}
}
Say stockCount
is -1
when DecrementStock
is called. The if condition will cause stockCount--
to be skipped, then stockCount
will still be -1
and trigger Debug.Assert
.
If these are supposed to be the only functions that touch stockCount
, then either
IncrementStock
is invoked so many times that the value overflows
or
DecrementStock
is called from multiple threads without synchronization
Based on your comment, I think unsynchronized access from multiple threads is indeed the problem.
精彩评论