Peyman
Peyman

Reputation: 3138

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
{
   private int stockCount = 0;

   public void DecrementStock ()
   {
      if ( stockCount > 0 )
         stockCount--;

      Debug.Assert ( stockCount >= 0 )
   }

   public void IncrementStock()
   {
      stockCount ++;
   }
}

Upvotes: 0

Views: 162

Answers (2)

Richard Schneider
Richard Schneider

Reputation: 35464

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 ++;
        }
    }
 }

Upvotes: 4

Ben Voigt
Ben Voigt

Reputation: 283893

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.

Upvotes: 4

Related Questions