Cross-thread operation not valid: .NET Cross Threading To Update Form Control


Cross-thread operation not valid

Cross-thread operation not valid

So you get the “Cross-thread operation not valid” error because you are trying to update an object on your form from a thread. I am not going to try to “glamor” you (True Blood reference) with fundamentals of delegates, threading, etc. If that is what you are looking for, search Google and you will find tons of references that are overly complicated using all of the proper terminology that typically makes my head hurt. I WILL show you the few bits of code in Visual Basic that are needed to get around the error. Or perhaps you just need to update a form control from a background process so the application does not hang.

In the example below, I am needing to update a ListBox control from a separate thread.  I need 2 items: a method to update the ListBox which takes a string as a parameter and a Delegate with a matching parameter signature.

Here is the Delegate:

Private Delegate Sub UpdateListboxDelegate(ByVal s As String)

And here is the method that actually updates the ListBox:

Private Sub UpdateListbox(ByVal s As String)
   If Me.InvokeRequired Then
      Me.BeginInvoke(New UpdateListboxDelegate(AddressOf UpdateListbox), New Object() {s})
      Return
   End If
   ListBox1.Items.Add(s)
End Sub

Here would be a sample of the main sub that is slow to process:

Public Sub LongProcess()
   For i As Integer = 0 To 100
      System.Threading.Thread.Sleep(5000)
      UpdateListbox("Currently on count: " & i)
   Next
End Sub

Now to kick off the thread:

ListBox1.Items.Clear()
Dim thread As New Threading.Thread(AddressOf LongProcess)
thread.Start()

That’s it!  The easiest solution without getting overly complicated.

…and in case you are looking for C# (it’s growing on me too):

        private delegate void UpdateListboxDelegate(string s);

        private void UpdateListbox(string s)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new UpdateListboxDelegate(UpdateListbox), new object[] { s });
                return;
            }
            listBox1.Items.Add(s);
        }

        public void LongProcess()
        {
            for (int i = 0; i < 10; i++)
            {
                System.Threading.Thread.Sleep(1000);
                UpdateListbox("Currently on count: " + i.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            System.Threading.Thread thread = new System.Threading.Thread(LongProcess);
            thread.Start();
        }

, ,

Comments are closed.