2012-03-21 39 views
0

我正在開發一個控制硬件設備的Windows Forms應用程序。我有一個關閉設備的按鈕。點擊事件如下所示:爲什麼我的命令不能立即執行,除非我使用MessageBox.Show()?

Private Sub btnTurnOff_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ 
    Handles btnTurnOff.Click 

    device.SetOff() 'Turn off the device 
    system.threading.thread.sleep(2000) 'Pause for 2 seconds 
End Sub 

奇怪的是,該設備直到2秒後才關閉。暫停,但如果我在SetOff()命令後立即插入MessageBox,則設備會在2秒之前立即關閉。暫停:

Private Sub btnTurnOff_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ 
    Handles btnTurnOff.Click 

    device.SetOff() 'turn off the device 
    MessageBox.Show("Device is now off") 
    system.threading.thread.sleep(2000) 'Pause for 2 seconds 
End Sub 

爲什麼這段代碼的行爲是這樣的?

+0

'MessageBox.Show'被阻塞,所以直到你點擊「OK」,它纔會進入'Thread.Sleep'。 – vcsjones 2012-03-21 19:04:04

回答

2

因爲你睡覺的線程...

所以程序什麼也不做兩秒鐘。添加消息框使程序繼續,然後,線程進入休眠狀態。

0

線程在睡覺時什麼也不做,它在那裏發生。 當您顯示消息框時,線程仍在運行。

嘗試快速測試,像

For i As Integer = 0 To 100 
    system.threading.thread.sleep(20) 
Next 

一個更好的辦法是

Do While [Device Is On] 
    system.threading.thread.sleep(100) 
Loop 

一個更好的方法是,如果device.SetOff()將調用一個事件,當它完成了什麼它在做。

0

您需要切換兩個並將Sleep置於MessageBox之前。

+0

爲什麼?考慮爲OP提供更多信息以跟進。 – rayryeng 2014-05-21 20:52:52

相關問題