I want to access selections from a listbox on my GUI from my backgroundworker. Without any additional changes trying to do such throws this error
Cross-thread Operation Not Valid: Control '_ListBox1' accessed from a thread other than the thread it was created on
The option I saw to avoid this is to use Invoke
by the following syntax, but is this .Net 4
(or higher) acceptable?
var selectedItems = (IList)this.Invoke(new Func<IList>(() => Listbox1.SelectedItems.Cast<object>().ToList()));
For a clearer picture this is how I want to access listbox items from my backgroundworker
namespace clown
{
public partial class Form1 : Form1
{
public Form1()
{
ListBox1.Items.Add("Firefly");
ListBox1.Items.Add("Hellfire");
}
private void btn1234_Click()
{
backgroundworker1.RunWorkerAsync();
}
private void backgroundworker1_DoWork(object sender, DoWorkEventArgs e)
{
//Long Running Process taking place here
//then we hit this
if (ListBox1.SelectedItems.Contains("Firefly")) { //take this course }
if (ListBox1.SelectedItems.Contains("Hellfire)) { //take this course }
}
}
}