C# – Updating a ListView from a new thread (multi-thread)

If you’re using ListViews in c# (Winforms or WPF – like a ListBox – but better), you’ve probably wanted to update the ListView data (ItemsSource – I also hope you’re using binding) without blocking the UI. Below is a simple method I’ve used that seems to work well, and allows you to pass parameters if needed. You can also download the entire project at: https://github.com/cbitting/ListViewUpdateMultiThread

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace wpfMultiThreadListViewUpdate
{
    public class Person
    {
        public string Name { get; set; }
    }

    public partial class MainWindow : Window
    {
        private Thread _thread;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            _thread = new Thread(() => showSomePeople(new Random().Next(4, 15), lstvwPeople));
            _thread.Start();
        }

        private void showSomePeople(int numberToGet, ListView listvw)
        {
            List<Person> somePeople = getSomePeople(numberToGet);

            Dispatcher.BeginInvoke(new Action(delegate()
            {
                listvw.ItemsSource = somePeople;
            }));
        }

        private List<Person> getSomePeople(int numberToGet)
        {
            List<Person> peeps = new List<Person>();

            for (int i = 0; i < numberToGet; i++)
            {
                peeps.Add(new Person() { Name = randomName() });
                Thread.Sleep(200);
            }

            return peeps;
        }

        private string randomName()
        {
            const string chrs = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            Random rdm = new Random();
            return new string(Enumerable.Repeat(chrs, 6)
              .Select(s => s[rdm.Next(s.Length)]).ToArray());
        }
    }
}
C# – Updating a ListView from a new thread (multi-thread)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s