Thread.Sleep(300)无法正常工作 [英] Thread.Sleep(300) not working correctly

查看:279
本文介绍了Thread.Sleep(300)无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望它执行代码的第一部分,然后使pictureBox可见,暂停3秒钟,隐藏pictureBox并执行其余代码:

I want it to execute the first part of the code, then make the pictureBox visible, pause for 3 seconds, hide the pictureBox and execute the rest of the code:

// first part of the code here
pb_elvisSherlock.Visible = true;
Thread.Sleep(300);
pb_elvisSherlock.Visible = false;
// rest of the code here

但是它执行整个代码块,然后才暂停.任何想法该怎么办?

But it executes the whole block of code and only then pauses. Any ideas what to do?

谢谢!

推荐答案

pb_elvisSherlock.Visible = true;
Application.DoEvents(); //let the app show the picturebox
Thread.Sleep(3000);
pb_elvisSherlock.Visible = false;

问题是您没有在暂停GUI线程之前让消息循环有机会显示图片框. Application.DoEvents()解决这个问题.

The problem is that you don't give the message loop a chance to display the picture box before you pause the GUI thread. Application.DoEvents() solve that.

请注意,在GUI线程上使用Thread.Sleep将使绘画冻结(在Sleep处于活动状态时,尝试在应用上移动一个窗口).

Note that using Thread.Sleep on the GUI thread will make the painting freeze (try move a window over your app when the Sleep is active).

您应该执行以下操作:

pb_elvisSherlock.Visible = true;
int counter = 0;
while (counter < 30)
{
  Application.DoEvents(); 
  Thread.Sleep(100);
  ++counter;
}
pb_elvisSherlock.Visible = false;

这仍然是一种hack,但是窗口将被重新绘制并根据需要进行响应.

It's still kind of a hack but the window will be redrawn and respond as it should.

更新2

好吧. DoEvents似乎有点过分. (感谢您的评论).

Well. DoEvents seems to be a bit to much of a hack. (thanks for the comments).

如果图片框是一种导航屏幕,请执行以下操作:

If the picturebox is a kind of a nag screen do something like this:

替代1

Alternative 1

  1. 创建一个仅包含图片框的新表单(不要在该表单上使用边框).
  2. 在该表单中添加一个计时器,该计时器会在三秒钟后调用Close
  3. 调用'myNagForm.DoModal()'

该解决方案可防止您的用户在看到nagform时以常规"形式进行任何操作.

That solution prevents your users from doing anything in your "normal" form while the nagform is visible.

替代2

Alternative 2

  1. 创建后台工作者,请参见此处: http://dotnetperls.com/backgroundworker
  2. 将您的图片框及其后执行的代码移动到后台工作程序方法中.

这篇关于Thread.Sleep(300)无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆