0

I'm write simple application to load csv file,and in c# code start the new thread to load heavy csv file with this code:

Thread workerThread = new Thread(DoWork);
workerThread.Priority = ThreadPriority.Highest;
workerThread.Start();


and into the DoWork i try run this code:

 public void DoWork()
 {
 label1.Text = "ok";
 }


but when receive label line i get this error:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

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


What happen?thanks.

Tharif
  • 13,794
  • 9
  • 55
  • 77
behzad razzaqi
  • 1,503
  • 2
  • 18
  • 33

1 Answers1

6

This is a common mistake on multi-threaded app when trying to access the UI controls from a non-UI thread. Accessing UI controls from a different thread than the one creating that control is not allowed. I normally turn the invocation from non-UI thread to the UI thread by using this:

    private void DoWork()
    {
        if (label1.InvokeRequired)
        {
            // this will be called by the non-UI thread
            label1.Invoke(new Action(DoWork));
        }
        else
        {
            // the actual implementation of the DoWork method, this will be called by the UI thread
            label1.Text = "Ok";
        }
    }
Tran Nguyen
  • 1,341
  • 10
  • 15