Search code examples
c#multithreadinglockingwindows-forms-designerinvoke

Windows form freezing when trying to use multithreading to populate large data set into a combox?


I'm trying to populate a list of around 3000 words into a windows form combobox dropdown menu. It was taking a long time doing it in one iteration loop, so i decided to use multi threading to have a thread do the same work on a third of the list. It runs faster, but im noticing it freezing a lot when the threads are running. Im not sure if it an issue with locking or if it just takes long to populate a combobox item list.

Ive tried using method invokers, but I feel like im using them wrong in this case.

I have these threads started:

Thread threadmid = new Thread(splitMidThird);
Thread threadtop = new Thread(splitTopThird);

threadmid.Start();
threadtop.Start();

private void splitMidThird()
{
  int thirds = totalPartNumber.Count() / 3;
  if (PartNumber_Text.InvokeRequired)
  {
    PartNumber_Text.BeginInvoke(new MethodInvoker(delegate
    {
      for (int index = thirds; index <= thirds * 2; index++)
      {                                
        PartNumber_Text.Items.Add(totalPartNumber.ElementAt(index));
      }
    }));
  }
  return;
}

private void splitTopThird()
{
  int thirds = totalPartNumber.Count() / 3;
  if (PartNumber_Text.InvokeRequired)
  {
    PartNumber_Text.BeginInvoke(new MethodInvoker(delegate
    {
      for (int index = thirds * 2; index <= totalPartNumber.Count() - 1; index++I)
      {                        
        PartNumber_Text.Items.Add(totalPartNumber.ElementAt(index));
      }
    }));
  }
  return;
}

The form just freezes when i try this.


Solution

  • Use the AddRange() method:

    When using this method to add items to the collection, you do not need to call the BeginUpdate and EndUpdate methods to optimize performance.

    Something like:

    PartNumber_Text.Items.AddRange(totalPartNumber.ToArray());