vb.net

執行緒 Task避免程式畫面當掉(VB.NET)

每次都忘記怎寫又在那邊找 乾脆自己紀錄一下

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
Be the First to comment.

Leave a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

(若看不到驗證碼,請重新整理網頁。)