Tuesday, December 18, 2012

[C#][FIX] Cross-thread operation not valid in Winforms with threads.

A common problem using WinForms in Visual Studio is syncing between logic threads and UI threads. Most winform applications should use a method to sync between both; otherwise, you will see the Form freeze while waiting for the logic to complete.

The following shows an example of calling a function that creates a delegate to do cross-thread operations.


private void ThreadSafeFunction(int intVal, bool boolVal)
    if (this.InvokeRequired)
            new MethodInvoker(
            delegate() { yourMethod(intVal, boolVal); }));
        //use intval and boolval

To use this method of cross-thread operations, call the ThreadSafeFunction in your logic thread.

In the curly brackets if the new delegate (), place any UI logic that needs to be done (i.e. yourTextbox.Text = intVal)

After you have updated the code to work with your WinForm, try it out and let us know how it goes!


Post a Comment