where is problem?
Well you're explicitly saying that you want to execute the task in the UI thread... and then you're sleeping within the task, so it's blocking the UI thread. How did you expect to be in the UI thread, but for Thread.Sleep
not to cause a problem?
If you can use C# 5 and async/await, that would make things much easier:
private static async Task ShowCitiesAsync()
{
for (int i = 0; i < 10; i++)
{
listBox1.Items.Add("Number cities in problem = " + i);
await Task.Delay(1000);
}
}
If you can't use C# 5 (as suggested by your tags), it's significantly trickier. You might be best off using a Timer
:
// Note: you probably want System.Windows.Forms.Timer, so that it
// will automatically fire on the UI thread.
Timer timer = new Timer { Interval = 1000; }
int i = 0;
timer.Tick += delegate
{
listBox1.Items.Add("Number cities in problem = " + i);
i++;
if (i == 10)
{
timer.Stop();
timer.Dispose();
}
};
timer.Start();
As you can see, it's pretty ugly... and it assumes you don't want to actually do any work between UI updates.
Another alternative would be to simulate your long-running task (sleeping at the moment) on a different thread using BackgroundWorker
, and use ReportProgress
to come back to the UI thread to add the list item.