Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-thread operation not valid [duplicate]

You can't. UI operations must be performed on the owning thread. Period.

What you could do, is create all those items on a child thread, then call Control.Invoke and do your databinding there.

Or use a BackgroundWorker

    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += (s, e) => { /* create items */ };
    bw.RunWorkerCompleted += (s, e) => { /* databind UI element*/ };

    bw.RunWorkerAsync();

When you access the from's property from another thread, this exception is thrown. To work around this problem there's at least 2 options.

  1. Telling Control to don't throw these exceptions (which is not recommended):

    Control.CheckForIllegalCrossThreadCalls = false;

  2. Using threadsafe functions:

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