2014-06-13 141 views
-1

我有一個程序,我想顯示一個文本,等待2秒,然後退出。當我運行它時,它等待兩秒鐘並退出,但不顯示文本。在C#中暫停執行

代碼:

if (userNumber == selectedNumber) 
{ 
    userMSGLabel.Text = "You guessed the correct number. Program is exiting"; 
    userMSGLabel.BackColor = Color.LightGreen; 
    System.Threading.Thread.Sleep(2000); 
    Environment.Exit(-1); 
} 

有什麼想法?

+0

你可以嘗試在你的'Thread.Sleep'調用之前添加一個'Application.DoEvents',它將在把線程置於睡眠狀態之前呈現你的屏幕。否則,我只是使用下面的答案建議的計時器,他們所概述的原因:) –

+2

爲什麼使用'Environment.Exit'來結束程序?你不能只調用主窗體的'Close'方法嗎? –

+0

@JimMischel - 如果他需要自定義的返回碼,比如'-1',他可能必須使用'Environment.Exit'。 – Icemanind

回答

0

嘗試使用計時器而不是thread.sleep。我不能從你的代碼中知道,但是你可能在GUI線程中,這會阻止重畫屏幕。

0

Thread.Sleep將當前線程阻塞指定的時間,並且您在UI線程中,該線程用於更新標籤。改變這種最簡單的方法可能是用添加一個計時器控件(你似乎是使用Windows窗體)的Interval 2000:

private void CloseTimer_Tick(object sender, EventArgs e) { 
    Environment.Exit(-1); // Can’t you just use Close() or something? 
} 

和,而不是睡覺和退出,

CloseTimer.Start(); 

在一般情況下,你也可以開始在其他幾種方法之一另一個線程,包括但不限於:

  • Using thread pool threads

  • Using System.Timers timers

  • 使用全螺紋:

    Thread t = new Thread(delegate { 
        Thread.Sleep(2000); 
        Environment.Exit(-1); 
    }); 
    
    t.Start(); 
    
  • 使用任務,@Max寫道;這是特別好的

  • 使用Application.DoEvents(但不要;這是邪惡的,你的UI仍然會鎖定,只需用一個正確的標籤;在一個循環做是多餘的;使用其他的事情之一)

4

我認爲你的Thread.Sleep(2000)阻塞了UI線程。請嘗試

private void Form1_Load(object sender, EventArgs e) 
{ 
    label1.Text = "You guessed the correct number. Program is exiting"; 
    label1.BackColor = Color.LightGreen; 
    Task.Factory.StartNew(Sleep).ContinueWith(t => Exit()); 
} 

private void Sleep() 
{ 
    Thread.Sleep(2000); 
} 

private void Exit() 
{ 
    Environment.Exit(-1); 
} 
-1

您可以使用Application.DoEvents()來請求Windows重新繪製您的標籤。

if (userNumber == selectedNumber) 
{ 
    userMSGLabel.Text = "You guessed the correct number. Program is exiting"; 
    userMSGLabel.BackColor = Color.LightGreen; 
    Application.DoEvents(); 
    System.Threading.Thread.Sleep(2000); 
    Environment.Exit(-1); 
} 
+0

我不知道爲什麼我得到-1,它在這個問題上正常工作。 –