在 Thread.Sleep() 期间保持 UI 响应 [英] Keeping UI responsive during a Thread.Sleep()
问题描述
背景:我正在编写一个应用程序,它遍历服务器列表并获取有关每台机器的各种详细信息.在迭代过程中,我需要更新表单上的各种控件(以显示所获得信息的摘要).因为它正在遍历一个列表,所以我调用了 Thread.Sleep() 以允许用户在询问下一台机器之前有时间阅读信息.下面是我的代码:
Background: I am writing an application that iterates through a list of servers and obtains various details about each machine. During the iteration, I need to update various controls on the form (to display a summary of the obtained information). Because it is iterating through a list, I have called a Thread.Sleep() to allow the user time to read through the information before the next machine is interrogated. Below is my code:
Task TestTask = Task.Factory.StartNew(() =>
{
foreach (String IpAddress in ServersToCheck)
{
if (IpAddress != String.Empty)
{
ServerBeingCheckedLabel.Text = IpAddress;
if (PingServer(IpAddress) == true)
{
PingChar_Label.ForeColor = Color.Green;
PingChar_Label.Text = "a";
CheckPermissionsAreValid(IpAddress);
}
else
{
PingChar_Label.ForeColor = Color.Red;
PingChar_Label.Text = "r";
PermChar_Label.ForeColor = Color.Red;
PermChar_Label.Text = "r";
}
}
}
Thread.Sleep(10000);
this.BackColor = FormBackGroundColor;
TestButton.Enabled = true;
RunTimer.Enabled = true;
}, CancellationToken.None, TaskCreationOptions.None, UiScheduler);
这对于更新表单上的控件很有效,但在 Thread.Sleep() 期间 UI 锁定.当然,如果 Thread.Sleep() 在一个单独的任务上被调用,UI 线程一直保持畅通无阻?
This works fine regarding updating the controls on the form, but during the Thread.Sleep() the UI locks up. Surely if the Thread.Sleep() is called on a separate task, the UI thread has remained unblocked?
推荐答案
Task.Delay 应该适合您的需求.
改变
Task.Factory.StartNew(() =>
到
Task.Factory.StartNew(async () =>
和改变
Thread.Sleep
到
await Task.Delay
这篇关于在 Thread.Sleep() 期间保持 UI 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!