Accessing a listview’s Items From Another Thread

The Problem at Hand

The other day I had a simple problem that I couldn’t seem to find an answer to online. I had a background worker running on a thread that needed to access a collection of listview items. The problem should be evident to most developers, I cannot access a control that was created via another thread.

If you try, you will get this all too familiar error:

“Cross-thread operation not valid: Control ‘listView1′ accessed from a thread other than the thread it was created on.”

What was my solution?

Create a delegate that returns the collection in a string list. Simple, yes, effective? You bet.

private delegate List GetListViewDelegate();

        private void btnStartThread_Click(object sender, EventArgs e)
        {
            //Start the worker thread
            var myWorker = new BackgroundWorker();
            myWorker.DoWork += WorkerThread;
            myWorker.RunWorkerAsync();
        }

        private void WorkerThread(object sender, DoWorkEventArgs e)
        {
            //Grab the list via the delegate I created
            var myList = (List)Invoke(new GetListViewDelegate(GetListViewItems));
            foreach (string item in myList)
            {
                MessageBox.Show(item);
            }
        }

        public List GetListViewItems()
        {
            //Return the list back to the delegate
            var pathList = new List();
            foreach (ListViewItem item in listView1.Items)
                pathList.Add(item.Text);
            return pathList;
        }

PLEASE NOTE: My syntax highlighter omitted the <string> type elements. “List” should be “List<string>”!

Solution Files

I’ve included a source file so you can try it out yourself.
Download it here

Share and Enjoy:
  • Print
  • Digg
  • Twitter
  • DotNetKicks
  • del.icio.us
  • Facebook
  • Mixx

0 Response to “Accessing a listview’s Items From Another Thread”


  • No Comments

Leave a Reply