當程式處理過程中,如有耗費時間的情況,通常會導致程式畫面當掉,為了避免這種情況發生,會把耗費時間的程式移到其他執行緒執行,在 .Net Framework 4.0中提供了 Task 類別,Task 類別簡化了 .Net Framework 中執行緒的撰寫,以下提供一個 Task 範例,當按下 Button2 按鈕後程式會停止 5 秒(模擬程式畫面當掉),當按下Button1 按鈕後,程式會開始一個執行緒,執行 run 函式,因 run 函式使用執行緒執行,執行時不會導致程式畫面當掉。

 

環境:.Net Framework 4.0

程式畫面:畫面中加入一個 TextBox 跟兩個Button

 

 

程式:
 

Imports System.Threading

 

Public Class Form1

 

   '當按下 Button 1 後,程式開始 Timer,每5秒鐘觸發

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

       '建立執行緒,執行 run 函式

       Dim t As Threading.Tasks.Task = Threading.Tasks.Task.Factory.StartNew(AddressOf run)

   End Sub

 

   Sub run()

       '更新 UI

       SetUI("執行緒開始", TextBox1)

 

       '停止 5 秒

       Thread.Sleep(5000)

 

       '更新 UI

       SetUI("執行緒結束", TextBox1)

   End Sub

 

   '設定 UI

   Private Delegate Sub UpdateUI(ByVal msg As String, ByVal con As Control)

   Sub SetUI(ByVal str As String, ByVal con As Control)

       If Me.InvokeRequired() Then

           Dim um As New UpdateUI(AddressOf SetUI)

           Me.Invoke(um, str, con)

       Else

           TextBox1.Text = str

       End If

   End Sub

 

   '當按下 Button 2 後,程式會停止 5 秒,程式畫面無法動作

   Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

       Thread.Sleep(5000)

   End Sub

 

End Class


 


 

參考資料:

https://msdn.microsoft.com/zh-tw/library/system.threading.tasks.task(v=vs.110).aspx

 

arrow
arrow
    全站熱搜

    iammic 發表在 痞客邦 留言(0) 人氣()