2

I have the following method:

/// <summary>
/// Gets the specified side of trades.
/// </summary>
/// <param name="tradesDictionary">The trades dictionary.</param>
/// <param name="side">The side.</param>
public IEnumerable<TradeRecord> GetTrades(Dictionary<Guid, TradeRecord> tradesDictionary, Side side)
{
    return (from tradeRecord in tradesDictionary.Values.ToList().AsParallel()
            where (tradeRecord.OrderRecord.PairRecord.Id == _pairId)
               && (tradeRecord.Side == side.ToString())
            orderby tradeRecord.Date, tradeRecord.DateCreated, tradeRecord.Id
            select tradeRecord);
}

Which causes the following exception:

Destination array is not long enough to copy all the items in the collection. Check array index and length.

The dictionary passed in, is constantly increasing in size. I wasn't getting the error before, the only thing that has changed is the volume of data in the tradesDictionary.

  1. Why does this exception happen?
  2. How do i prevent it from happening?

1 Answer 1

3

"The dictionary passed in, is constantly increasing in size"

Do you mean that it's being modified while you're executing this code? That's a no-no. I suspect the ToList call is failing due to this. (After ToList() has executed, the list should be effectively separate from the dictionary.)

Basically Dictionary<TKey, TValue> doesn't support concurrent reading and writing. You might want to look at ConcurrentDictionary<,> which allows you to iterate over it while another thread is writing.

One suggestion to improve performance when it's all working: call side.ToString() once at the start of the method, instead of on every single loop iteration.

Sign up to request clarification or add additional context in comments.

1 Comment

Changed my volatile Dictionary objects to ConcurrentDictionary and i am no longer receiving the error. I also did what you recommended at the start of my query - it does improve performance, but is negligible. As the dictionary grows, i'm sure the performance gain will become more noticeable. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.