I'm confused why the output of these 2 programs differs:
private async void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 33; i++)
{
await LongProcess();
}
}
private async Task LongProcess()
{
await Task.Delay(1000);
progressBar1.Value += 3;
}
and
private async void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 33; i++)
{
await Task.Run(() => LongProcess());
}
}
private async void LongProcess()
{
await Task.Delay(1000);
progressBar1.Value += 3;
}
I realize the first example returning Task
is more correct, but I don't understand why wrapping the void function in a Task.Run
doesn't produce the same output? The first function does what I expect, updates the progress bar every 1 second. The second code attempts to update the progress bar all at once, causing problems attempting to update the same UI element from multiple threads.
My assumption was since the buttonClick method awaits the long process to complete, both sets of code should not allow the progressBar1 update to happen until the previous process has completed. Why does the second set of code allow it to happen all at once?