2
How can I modify the values of an interface control within a separate task from the main thread?
Example:
private void button1_Click(object sender, EventArgs e)
{
Task task = new Task(Processar);
task.Start();
}
public void Processar()
{
try
{
int i = 0;
this.progressBar1.Maximum = 5000000;
for (i = 0; i < this.progressBar1.Maximum; i++)
{
this.progressBar1.Value = i;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When running this little snippet of code I get this msg...
Cross-thread Operation not Valid: Control 'progressBar1' accessed from a thread other than the thread it was created on
I tried to use delegate, but it didn’t work out so well.
Usa
Task.Run(() => ...)
instead ofnew Task()
andtask.Start()
.– dcastro