コード例 #1
0
 //This method is thread-safe but since it doesnt use any locks it is not atomic. Inbetween the 2 method calls, another thread can sneak in to change the value. However due to the logic of the application, that doesn't matter. As long as the _totalQuantity is getting uodated there isnt any need to worry about race condition.
 public void BuyStock(SalesPerson person, string item, int quantity)
 {
     //TryUpdate cannot be used becasue the currentValue (oldValue) is not known
     _stock.AddOrUpdate(item, quantity, (key, oldValue) => oldValue + quantity);
     Interlocked.Add(ref _totalQuantityBought, quantity);    //Thread-Safe
     _toDoQueue.AddTrade(new Trade(person, -quantity));
 }