I want to delay loading data anywhere between 1 and 20 seconds. I also want to update the UI with the countdown to update like "Updating data in x..."
I can do Task.Delay, or DispatcherTimer or Aysnc/await but how do I update the UI with every second countdown ?
Sample to put my point across (it won't work for me since this is blocking UI thread).
private void Update()
{
var random = new Random();
var counter = random.Next(1, 20);
for (int i = counter; i > 0; i--)
{
UpdateCounter = i;// property bound to UI to update the countdown
Thread.Sleep(1000); //
}
// some function to update data...
}
There are a lot of options how to do it. I implemented 2 of them. I would recommend second, but it depends on your needs.
private void Update1()
{
Task.Factory.StartNew(() =>
{
var random = new Random();
var counter = random.Next(1, 20);
for (int i = counter; i > 0; i--)
{
Dispatcher.Invoke(() => UpdateCounter = i);
Task.Delay(1000).Wait();
}
Dispatcher.Invoke(// some function to update data...);
}
);
}
private async Task Update2()
{
var random = new Random();
var counter = random.Next(1, 20);
for (int i = counter; i > 0; i--)
{
UpdateCounter = i;
await Task.Delay(1000);
}
// some function to update data...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.