edit: Application.DoEvents(); this did it. found here: Force GUI update from UI Thread
c#, winforms. i want to increase a number by steps of 1 and have those increments shown inside a listview, so that the user sees the number counting up (for example from 10 to 15).
i have another button that increments just by 1 when clicked and uses the same display(). it works fine and updates the display as expected.
i tried these codes (shortened to save space here):
(1)
for (int i = 0; i < 5; i++)
{
var t = Task.Run (async () =>
{
myInt++;
await Task.Delay(300);
display(); //forces screen refresh
});
}
(2)
for (int i = 0; i < 5; i++)
{
var t = Task.Run (() =>
{
myInt++;
Task.Delay(300).Wait;
display();
});
//t.Wait(); //causes "An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll"
}
(3)
for (int i = 0; i < 5; i++)
{
myInt++;
display();
System.Threading.Thread.Sleep(300);
}
(4)
Stopwatch stopwatch = new Stopwatch();
for (int i = 0; i < 5; i++)
{
stopwatch.Restart();
while (true)
{
if (stopwatch.ElapsedMilliseconds >= 300)
{
break;
}
}
stopwatch.Stop();
myInt++;
display();
}
all use this:
private void display()
{
myListView.Items.Clear();
myListView.Items.Add(new ListViewItem(new[] { myInt }));
}
(1) and (2) increment the number by 5 but the display is not updated at all. it shows when the display is updated by some other function.
(3) and (4) increment the number by 5, but the display is only updated after about 1500ms, the display skipping the single steps and displaying just the final result (eg 15).
any suggestions to make this work? can i force a refresh in the display() function somehow?
why does t.Wait(); cause an exception? (i found the task code somewhere on the net)
edit:
(5)
private void team_comm_btn_all_Click(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
await Run(i); //error 74 see below
}
}
private async Task Run(int i)
{
myInt++;
display();
await Task.Delay(300);
}
await Run(i); gives the following: Error 74 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
just doing "Run(i)" instead gives a warning that "await" is missing... in this case it compiles and increments by 5 without any delay.
(6)
private void team_comm_btn_all_Click(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
var task = Task.Run(async () =>
{
await Run(i);
});
}
}
private async Task Run(int i)
{
myInt++;
display();
await Task.Delay(300);
}
increments by 5 but does not update display at all.