Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8326217
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T00:41:45+00:00 2026-06-09T00:41:45+00:00

I am getting a hard to reproduce error in the following program in which

  • 0

I am getting a hard to reproduce error in the following program in which a number of threads update a concurrent dictionary in parallel and the main thread displays the state of the dictionary in sorted order after fixed time intervals, until all updating threads complete.

public void Function(IEnumerable<ICharacterReader> characterReaders, IOutputter outputter)
{
    ConcurrentDictionary<string, int> wordFrequencies = new ConcurrentDictionary<string, int>();
    Thread t = new Thread(() => UpdateWordFrequencies(characterReaders, wordFrequencies));
    bool completed = false;
    var q = from pair in wordFrequencies orderby pair.Value descending, pair.Key select new Tuple<string, int>(pair.Key, pair.Value);
    t.Start();
    Thread.Sleep(0);

    while (!completed)
    {
        completed = t.Join(1);
        outputter.WriteBatch(q);
    }            
}

The function is given a list of character streams and an outputter. The function maintains a concurrent dictionary of word frequencies of words read from each of the character streams (in parallel). The words are read in by a new thread, and the main thread outputs the current state of the dictionary (in sorted order) every 1 miliseconds until all the input streams have been read (in practice the outputting will be something like every 10 seconds, but the error only seems to be appearing for very small values). The WriteBatch function just writes to the console:

public void WriteBatch(IEnumerable<Tuple<string, int>> batch)
{
    foreach (var tuple in batch)
    {
        Console.WriteLine("{0} - {1}", tuple.Item1, tuple.Item2);
    }
    Console.WriteLine();
}

Most executions are fine, but sometimes I get the following error at the foreach statement in the WriteBatch function:

“Unhandled Exception: System.ArgumentException: The index is equal to or greater
than the length of the array, or the number of elements in the dictionary is gre
ater than the available space from index to the end of the destination array.”

The error does seem to go away if the main thread sleeps for a short while after starting the updating threads and before starting the display loop. It also seems to go away if the orderby clause is removed and the dictionary is not sorted in the linq query. Any explanations?

The foreach (var tuple in batch) statement in the WriteBatch function gives the error. The stack trace is as follows:

Unhandled Exception: System.ArgumentException: The index is equal to or greater
than the length of the array, or the number of elements in the dictionary is gre
ater than the available space from index to the end of the destination array.
at System.Collections.Concurrent.ConcurrentDictionary2.System.Collections.Ge
neric.ICollection>.CopyTo(K
eyValuePair2[] array, Int32 index)
at System.Linq.Buffer1..ctor(IEnumerable1 source)
at System.Linq.OrderedEnumerable1.d__0.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at MyProject.ConsoleOutputter.WriteBatch(IEnumerable1 batch) in C:\MyProject\ConsoleOutputter.cs:line 10
at MyProject.Function(IEnumerable1 characterReaders, IOutputter outputter)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T00:41:46+00:00Added an answer on June 9, 2026 at 12:41 am

    As others have said, there is a race in the constructor of the internal class System.Linq.Buffer<T>, which is called by OrderBy.

    Here is the offending code snippet:

    TElement[] array = null;
    int num = 0;
    if (collection != null)
    {
        num = collection.Count;
        if (num > 0)
        {
            array = new TElement[num];
            collection.CopyTo(array, 0);
        }
    }
    

    The exception is thrown when item(s) are added to the collection after the call to collection.Count but before the call to collection.CopyTo.


    As a work around, you can make a “snapshot” copy of the dictionary before you sort it.

    You can do this by calling ConcurrentDictionary.ToArray.
    As this is implemented in the ConcurrentDictionary class itself, it is safe.

    Using this approach means you don’t have to protect the collection with a lock which, as you say, defeats the purpose of using a concurrent collection in the first place.

    while (!completed)
    {
        completed = t.Join(1);
    
        var q =
          from pair in wordFrequencies.ToArray() // <-- add ToArray here
          orderby pair.Value descending, pair.Key
          select new Tuple<string, int>(pair.Key, pair.Value);
    
        outputter.WriteBatch(q);
    }            
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to format a result from a program but getting an hard time.
I am getting the following error from C++ Builder 2009's linker Unresolved external '__fastcall
I have a hard time getting started with a simple bluetooth example which has
It is getting very hard me to know at which line my code broke
I'm having a hard time getting a filter working. I'm roughly following the example
I am getting intermittent and hard to track CoreData exceptions when trying to delete
I'm having a hard time getting my head around this, and Google just isn't
I am having a hard time getting the correct data out of an array.
I'm having a hard time getting my AJAX requests to work on a staging
Im having a hard tim getting the NSDateFormatter to give me a correct date

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.