我经常看到它提到Thread.Sleep();不应该使用,但我不明白为什么会这样.如果Thread.Sleep();可能造成麻烦,是否有任何替代解决方案具有相同的安全性?
例如.
while(true)
{
doSomework();
i++;
Thread.Sleep(5000);
}
Run Code Online (Sandbox Code Playgroud)
另一个是:
while (true)
{
string[] images = Directory.GetFiles(@"C:\Dir", "*.png");
foreach (string image in images)
{
this.Invoke(() => this.Enabled = true);
pictureBox1.Image = new Bitmap(image);
Thread.Sleep(1000);
}
}
Run Code Online (Sandbox Code Playgroud) 我正在编写一个连续的轮询循环来监视某些事件发生,然后在UI线程上采取一些操作.
我正在编写以下代码
public static void HandlePopup(this HostedControl control, string className, string caption, System.Action callback)
{
var popupTask = Task.Factory.StartNew(() =>
{
Thread.Sleep(5000); // just wait for 5 seconds.
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).ContinueWith((prevTask) =>
{
AutomationElementCollection collection = null;
do
{
} while (true);
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).ContinueWith((prevTask) =>
{
if (!prevTask.IsFaulted)
{
if (control.InvokeRequired)
{
control.Invoke(callback);
}
else
{
callback();
}
}
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
try
{
////popupTask.Wait();
}
catch (AggregateException ex)
{
ex.Handle(exnew =>
{
return true;
}); …Run Code Online (Sandbox Code Playgroud) 背景:我正在编写一个应用程序,它遍历服务器列表并获取有关每台机器的各种详细信息.在迭代期间,我需要更新表单上的各种控件(以显示所获取信息的摘要).因为它正在遍历列表,所以我调用了Thread.Sleep()以允许用户有时间在查询下一台机器之前读取信息.以下是我的代码:
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);
Run Code Online (Sandbox Code Playgroud)
这在更新窗体上的控件时工作正常,但在Thread.Sleep()期间,UI会锁定.当然,如果在单独的任务上调用Thread.Sleep(),UI线程仍然未被阻塞?