简体   繁体   English

Thread.Sleep或Timer用于显示每个步骤

[英]Thread.Sleep or Timer for showing every step

I am making a game wumpus world in winforms in which an agent(computer) can move in 4 directions. 我正在用Winform制作一个游戏世界 ,其中代理(计算机)可以在4个方向上移动。 I am using button control for base and showing and hiding images where ever needed. 我正在使用按钮控制基础,并在需要时显示和隐藏图像。 i used Thread.Sleep for that but problem is that when i click button nothing is showing on form. 我使用Thread.Sleep,但问题是,当我点击按钮时,表格上没有显示任何内容。 the process on background is working fine but it is not showing each step. 后台进程运行良好,但未显示每个步骤。 and yes i am using Thread.Sleep in current UI Thread. 是的我在当前的UI线程中使用Thread.Sleep
I want to show every step to users with interval of 2 seconds. 我希望以2秒的间隔向用户显示每一步。

Using Thread.Sleep is a poor design choice for several reasons: 使用Thread.Sleep是一个糟糕的设计选择,原因如下:

  1. It blocks the thread for the duration of the time it is sleeping. 它会在休眠期间阻塞线程。
  2. It uses up threads in the thread pool, so this solution will not scale well at all. 它耗尽了线程池中的线程,因此该解决方案根本无法很好地扩展。
  3. It is a bad timing mechanism, because there is a time slice, or quantum, in play here that varies between operating systems and even versions of the same operating system (read: Windows). 这是一个糟糕的计时机制,因为这里有一个时间片或量子,在操作系统甚至同一操作系统的版本之间有所不同(阅读:Windows)。

This previous SO question gives more information about why Thread.Sleep is bad: 之前的SO问题提供了有关Thread.Sleep为什么不好的更多信息:

Why Is Thread.Sleep So Harmful 为什么Thread.Sleep如此有害

it's hard to answer without any code to go by, but the main problem as i understand it is that you change the look of the world, and then tell it to sleep, witch means nothing will be painted. 没有任何代码,很难回答,但是据我了解,主要问题是您改变了世界的面貌,然后告诉它入睡,女巫意味着什么都不会画。 and then when the thread wakes up, you again change the world and make it sleep. 然后当线程唤醒时,您将再次改变世界并使它进入睡眠状态。 nothing will be painted that way. 不会那样画任何东西。

better way to do it will be timer, make it a single timer and a queue of events that needed to be shown and you are on your way to do it. 更好的方法是定时器,使它成为一个单一的计时器和一个需要显示的事件队列,你正在去做。

are you working on winForms, because if you are working on WPF you can do much nicer things 你在winForms上工作,因为如果你正在研究WPF,你可以做更好的事情

Edit: I'm not saying that Timer is the best way to do it, but it's a good valid way 编辑:我不是说Timer是最好的方法,但这是一个很好的有效方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM