Locking in Deal, a couple of questions…

Since the class 'Deck' employs ConcurrentDictionary (CD), it seems I have made an implicit agreement to ensure concurrency throughout. To that end, I've used 'Lock'. Despite searching for an answer, I still have questions.

1.) Is there an implicit agreement? 2.) Is the scope of the lock correct? 3.) How would I test this code?

Thanks!

(PS: I am not a student.)

public ConcurrentDictionary<int, Card> Deal(ConcurrentDictionary<int, Card> hand, int cardsNeeded) { Debug.Assert(Cards != null, "ERROR: Cards is null upon invocation of Deck.Deal"); if (Cards.Count < cardsNeeded) throw new ArgumentOutOfRangeException();

 var valueFound = new Card(rank.Ace, suit.Club); // Card value is not used lock (dealLock) // Object private to Deck { IEnumerable<int> KeyCollection = Cards.Keys.Take(cardsNeeded); foreach (var key in KeyCollection) { if (Cards.TryRemove(key, out valueFound)) { if (!hand.TryAdd(key, valueFound)) { Debug.WriteLine("WARNING: TryAdd failed when adding card to Cards"); } } else Debug.WriteLine("WARNING: TryRemove failed when removing card from Cards"); } } return hand; } 

by SemanticAgitator via /r/csharp

Leave a Reply