暂停执行方法而不锁定GUI。 C#

我正在使用C#进行卡片游戏,参与我的OOP介绍文章并让游戏正常运行,但我正在为GUI添加“天赋”。

目前,卡片即时处理并显示在UI上。 我希望在交易卡之前暂停程序暂停一会儿。

当游戏启动时,以下代码运行以填充代表它们的PictureBox(最终将是一个循环):

cardImage1.Image = playDeck.deal().show(); cardImage2.Image = playDeck.deal().show(); cardImage3.Image = playDeck.deal().show(); cardImage4.Image = playDeck.deal().show(); cardImage5.Image = playDeck.deal().show(); ... 

我尝试使用System.Threading.Thread.Sleep(100); 在每个deal()。show()之间以及每个方法中,但它实现的只是锁定我的GUI,直到所有的睡眠处理完毕,然后一次显示所有的卡片。

我也试过使用计时器和while循环的组合,但它产生了相同的效果。

达到预期结果的最佳方法是什么?

问题是您在UI上运行的任何代码都将阻止UI并冻结程序。 当您的代码正在运行时(即使它正在运行Thread.Sleep ),发送到UI的消息(例如Paint或Click)将不会被处理(直到控制在您退出事件处理程序时返回到消息循环),导致它冻结。

执行此操作的最佳方法是在后台线程上运行,然后在睡眠之间Invoke UI线程,如下所示:

 //From the UI thread, ThreadPool.QueueUserWorkItem(delegate { //This code runs on a backround thread. //It will not block the UI. //However, you can't manipulate the UI from here. //Instead, call Invoke. Invoke(new Action(delegate { cardImage1.Image = playDeck.deal().show(); })); Thread.Sleep(100); Invoke(new Action(delegate { cardImage2.Image = playDeck.deal().show(); })); Thread.Sleep(100); Invoke(new Action(delegate { cardImage3.Image = playDeck.deal().show(); })); Thread.Sleep(100); //etc... }); //The UI thread will continue while the delegate runs in the background. 

或者,您可以制作计时器并在下一个计时器刻度中显示每个图像。 如果你使用计时器,你应该在开始时做的就是启动计时器; 不要等待它,否则你会引入同样的问题。

便宜的出路是循环调用Application.DoEvents(),但更好的选择是设置一个System.Windows.Forms.Timer,它会在第一次经过后停止。 在任何一种情况下,您都需要一些指示器来告诉您的UI事件处理程序忽略输入。 如果它足够简单,您甚至可以将timer.Enabled属性用于此目的。

通常,我只是推荐这样的函数来执行暂停,同时允许UI进行交互。

  private void InteractivePause(TimeSpan length) { DateTime start = DateTime.Now; TimeSpan restTime = new TimeSpan(200000); // 20 milliseconds while(true) { System.Windows.Forms.Application.DoEvents(); TimeSpan remainingTime = start.Add(length).Subtract(DateTime.Now); if (remainingTime > restTime) { System.Diagnostics.Debug.WriteLine(string.Format("1: {0}", remainingTime)); // Wait an insignificant amount of time so that the // CPU usage doesn't hit the roof while we wait. System.Threading.Thread.Sleep(restTime); } else { System.Diagnostics.Debug.WriteLine(string.Format("2: {0}", remainingTime)); if (remainingTime.Ticks > 0) System.Threading.Thread.Sleep(remainingTime); break; } } } 

但是,当从事件处理程序(例如按钮单击)中调用此解决方案时,似乎存在一些复杂性。 我认为系统希望按钮单击事件处理程序在继续处理其他事件之前返回,因为如果我在事件处理程序仍在运行时再次尝试单击,则按钮会再次按下,即使我正在尝试拖动表单而不是点击按钮。

所以这是我的选择。 在表单中添加一个计时器,并创建一个经销商类,通过与该计时器交互来处理卡片处理。 设置计时器的Interval属性以匹配您希望处理卡的时间间隔。 这是我的示例代码。

 public partial class Form1 : Form { CardDealer dealer; public Form1() { InitializeComponent(); dealer = new CardDealer(timer1); } private void button1_Click(object sender, EventArgs e) { dealer.QueueCard(img1, cardImage1); dealer.QueueCard(img2, cardImage2); dealer.QueueCard(img3, cardImage1); } } class CardDealer { // A queue of pairs in which the first value represents // the slot where the card will go, and the second is // a reference to the image that will appear there. Queue> cardsToDeal; System.Windows.Forms.Timer dealTimer; public CardDealer(System.Windows.Forms.Timer dealTimer) { cardsToDeal = new Queue>(); dealTimer.Tick += new EventHandler(dealTimer_Tick); this.dealTimer = dealTimer; } void dealTimer_Tick(object sender, EventArgs e) { KeyValuePair cardInfo = cardInfo = cardsToDeal.Dequeue(); cardInfo.Key.Image = cardInfo.Value; if (cardsToDeal.Count <= 0) dealTimer.Enabled = false; } public void QueueCard(Label slot, Image card) { cardsToDeal.Enqueue(new KeyValuePair(slot, card)); dealTimer.Enabled = true; } } 

我会尝试在另一个线程中放置处理牌组的代码(并调用Thread.Sleep)。