Wesman80
Wesman80

Reputation: 67

GETTING listboxitems from other thread: Cross-thread operation not valid

So far I have seen 1000 examples how to set items in listbox objects from a different thread using the Invoke method.

However, I cannot find any solution on how to simply read the items from a listbox from a background worker tread. How do I invoke this before reading the SelectedItems for example...

foreach (var item in CheckedListBox1.SelectedItems)
{
 //Do something
}

Above code running in the background worker generated the following error:

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

Upvotes: 2

Views: 1500

Answers (2)

User3810621
User3810621

Reputation: 540

You may similarly use Invoke to read UI elements from a background thread:

var selectedItems = (IList)this.Invoke(new Func<IList>(() =>
    CheckedListBox1.SelectedItems.Cast<object>().ToList()));

foreach (var item in selectedItems)
{
    //Do something
}

If you know the type of your items, you may specify the type in the Cast call, and return an IList<YourType> rather than the non-generic IList.

Upvotes: 1

Akku
Akku

Reputation: 4454

You'll need a reference to a UI object. Then you can use this code (.NET 4.0) to invoke stuff on the main thread when you don't have a reference, as you can use the Application.Current Pointer which is on the main thread:

Application.Current.Dispatcher.BeginInvoke((ThreadStart)delegate
{
    // TODO: Implement task to do on main thread
    foreach (var item in CheckedListBox1.SelectedItems)
    {
         //Do something
    }
});

Upvotes: 1

Related Questions