0

I have simple application. I have an arraylist and this list includes websites.

I have an error when I click the button. The error is ;

A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

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

If there is a handler for this exception, the program may be safely continued.

Codes are below:

    private void button2_Click(object sender, EventArgs e) {
        for (int i = 0; i < sitelist.Count; i++) {
            Thread thread = new Thread(getStatus);
            thread.Start((string)sitelist[i]);
        }
    }
    private void getStatus(Object obj) {
        listBox2.Items.Add("1");
    }

When I wrote the code like:

    private void getStatus(Object obj) {
         MessageBox.Show((string)obj);
    }

it works. Why it shows error when I use listbox ?

Sincerely. Ömer.

Community
  • 1
  • 1
OEASLAN
  • 150
  • 1
  • 1
  • 8
  • You can't access UI from another thread. See also [this post](http://stackoverflow.com/questions/9625700/listening-serial-port-how-to-add-string-to-listbox/9625765#9625765) or [this post](http://stackoverflow.com/questions/22890740/c-sharp-tcp-client-and-server-having-trouble/22890816#22890816) or [this post](http://stackoverflow.com/questions/10170448/how-to-invoke-a-ui-method-from-another-thread/10170699#10170699). – Adriano Repetti Jul 16 '14 at 15:14
  • Clearly, the `MessageBox.Show` method does not have the same threading restrictions that a listbox does. Asking how to update a listbox from another thread is a different question entirely. – Factor Mystic Jul 16 '14 at 15:15
  • MessageBox won't fail because it won't access any handle created on main thread BUT it'll fail if, for example, you press CTRL+C – Adriano Repetti Jul 16 '14 at 15:16

1 Answers1

2

You have to use BeginInvoke

 private void getStatus(Object obj) {
        this.BeginInvoke(new EventHandler((s,e)=>{listBox2.Items.Add("1")}));
    }

The reason is that you can't touch properties or affect the drawing of a WinForm control from any other thread than the main one. You have to marshall a call back to the main thread, and Invoke/BeginInvoke will do that for you.

Matt
  • 3,638
  • 2
  • 26
  • 33