Saul Llamas

Saul Llamas

  • NA
  • 1
  • 0

How to make thread safe call to a listview object

Oct 31 2007 9:34 AM

I get an Invalid Operation Exception error because the program is trying to make a cross-thread call to a listview object that was created by the main thread.

The basic operation of the program is that items can be added, removed, modified,and cleared for the listview component on the panel.  If I want, I can start a timer.  Meanwhile a 'listener' sits in another thread waiting for the time to elapse.  On this elapsed timer event, it enters the OnTimerDoThis() event-handler.  Within the event-handler, on the foreach line,  the 'Invalid Operation Exception' error occurs only after an item is added to the listview, or if an item  exists already.  I have put a comment at the end of the line ->  '//ERROR HAPPENS HERE' so that using Find will take you to that line.  The purpose of the foreach is to search the listview items and indicate if it matches to a string constant.

I was able to create a delegate for a radio component and able to handle the same exception error, but need to do the same for the listview.  Question is how do I get around the error?

FYI.  I am not using the background watcher.

The code for the async event-handler is as follows:

protected void OnTimerDoThis(Object source, ElapsedEventArgs e)

{

// immediatly disable timer after timeout interval reached

DisableTimer();

MessageBox.Show("Inside OnTimerDoThis asnyc event\n\nTimer Disabled\n\n" +

"Press OK to re-enable Timer");

foreach (ListViewItem item in lvData.Items) //ERROR HAPPENS HERE

{

if (matchString.StartsWith(item.Text))

{

MessageBox.Show("Inside match string and asnyc event\n\nTimer Disabled\n\n" +

"Press OK to re-enable Timer");

}

}

EnableTimer();

}