Edit form elements from a Thread
Categories: C, Source Code
Tags:
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.”

Working solution:
To allow that a thread can access to the form elements, you have to create a “delegate” where insert the information as parameters that you want to change in the thread form. E.G. the percentage of completion:
public delegate void SetProgressBarDelegate(int value);
Write the method code to assign to the delegate that change the progressBar value:
public void SetProgressBar(int value)
{
lock (this)
{
progressBar1.Value = value;
}
}
The lock waits that the form object is not used from another thread (is like using Monitor.Enter and Monitor.Exit) before executing the code in the lock statement.
Of course we need to invoke the SetProgressBar method in the thread:
public void threadProc()
{
for (int i = 1; i <= 10; i++)
{
Thread.Sleep(250);
this.progressBar1.Invoke(
new SetProgressBarDelegate(this.SetProgressBar), i * 10);
}
MessageBox.Show("Operation Completed!");
}
With this tip the program the thread will work right without illegal cross thread operations.
Download Form-Thread Interaction. Downloads: 229
Downloading the file you will find a ready example in form of a VS 2005 project.
Se sei interessato a questo post, potresti anche provare a leggere:
- No related posts
29 Sep 2007 dzamir
valtrex prophylaxis
Usandoprovigal
Usando