BackgroundWorker and ListView cross-thread exception

  • Thread starter Thread starter Jazza
  • Start date Start date
J

Jazza

Hi,

I am writing an application which displays a list of computers on a network
and then pings each one and displays the result.

To keep the UI responsive, I am doing the ping operation using a
BackgroundWorker component. The Ping method loops through a list of Computer
business objects, pings the name of the computer and stores the result in a
property of the Computer object called Result.

The Computer object also implements INotifyPropertyChanged interface, which
raises a PropertyChanged event when the Result property is modified.

I have an event handler in my form class which listens for the
Computer.PropertyChanged event, and attempts to update the corresponding
ListViewItem with the result of the ping.

However, as soon as I reference the ListView control, or any of the items, I
get:

Cross-thread operation not valid: Control 'ComputerListView' accessed from a
thread other than the thread it was created on.

How can I ensure the ListView gets updated?

Regards,

James
 
You should not call the UI thread from a worker. The call needs to be
marshalled back to the UI thread by one of several methods.

You can do it yourself by providing a method in your form or control to
update the listview and then "Invoke" this method from the background
thread.

Alternatively you can use the new WindowsFormsSynchronizationContext object
available in the 2.0 framework.

--
--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
Back
Top