Edit form elements from a Thread
Scenario:
The program has to execute a long operation (such as a downloaded file from the internet) when the user clicks on a button, but during the operation the user has the opportunity to interact with the program, and the program gives a visual feedback of the task completion percentage.
Easy, but not working, solution:
To solve a problem like that we need to use a Thread that executes the task in a separate context from the main Form, otherwise, if we execute the long operation in the onClick method of the button, the form will remain frozen during the task execution. The problem comes out when the program tries to update the form from the thread:
private void button1_Click(object sender, EventArgs e)
{
testThread = new Thread(threadProc);
testThread.Start();
}
public void threadProc()
{
// wast a lot of time...
for (int i = 1; i <= 10; i++)
{
Thread.Sleep(250);
progressBar.Value = i * 10;
}
MessageBox.Show("Operation Completed!");
}
Unfortunately, the code that assigns the value to the progressBar will produce an exception like that:
“Illegal cross-thread operation: Control ‘progressBar1′ accessed from a thread other than the thread it was created on.”

29 Sep 2007 dzamir 0 comments