Load ListBox Using ThreadPool in C#

ThreadPool is a class which contains a pool of threads. By using these threads, we can send work in the form of the delegate. Here we discuss how to load data into ListBox using ThreadPool class in C#.

Open Microsoft Visual Studio 2015 => Create Windows Application and name it as ListBoxThreadPool and add below code to the Form1.

using System;

using System.Windows.Forms; 

namespace ListBoxThreadPool

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        } 

        private delegate void Add(int i); 

        private void AddItem(int I)

        {

            listBox1.Items.Add("ListBox-" + i);

            Application.DoEvents();

        } 

        private void LoadListBox(object state)

        {

            for (int i = 0; i < 100000; i++)

                listBox1.Invoke(new Add(AddItem), new object[] { i });

        } 

        private void Form1_Load(object sender, EventArgs e)

        {

            System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(LoadListBox));

        }

    }

} 

As shown above w define the delegate to call LoadListBox() method. Inside LoadListBox() we are calling AddItem() method which doesn’t return any value. Run the application, and we get the output as below.

  

                                                                                                                      ListBoxThreadPool.zip