當執行緒為無窮迴圈時,如果需要中途停止執行緒,可以使用 CancellationTokenSource 類別,來達到此功能,以下提供一個取消執行緒範例,

當按下 Run 按鈕後,建立執行緒,執行 run 函式,函式中有一個無限迴圈,將 num 變數進行加 1後,將 num數值更新到 TextBox,持續執行,當按下 Stop 按鈕後,停止執行緒。

 

環境:.Net Framework 4.0

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

 

 

程式:

Imports System.Threading

Public Class Form1

   Dim num As Integer

   Dim tokenSource2 As CancellationTokenSource

   Dim ct As CancellationToken

 

   '當按下 Run 按鈕後,建立執行緒

   Private Sub btnRUN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRUN.Click

       num = 0

       tokenSource2 = New CancellationTokenSource()

       ct = tokenSource2.Token

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

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

   End Sub

 

   '當按下 STOP 按鈕後,將執行緒 Cancel

   Private Sub btnSTOP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSTOP.Click

       tokenSource2.Cancel()

   End Sub

 

   Private Sub run()

       ct.ThrowIfCancellationRequested()

       MsgBox("執行緒開始")

       While (True)

 

           If ct.IsCancellationRequested Then

               '離開執行緒

               MsgBox("執行緒結束")

               Exit Sub

           End If

 

           num = num + 1

 

           '更新 UI

           SetUI(num.ToString, TextBox1)

 

           '停止 1 秒

           Thread.Sleep(1000)

 

       End While

 

   End Sub

 

   '更新 UI

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

   Private Sub SetUI(ByVal msg As String, ByVal con As Control)

       If Me.InvokeRequired() Then

           Dim um As New UpdateUI(AddressOf SetUI)

           Me.Invoke(um, msg, con)

       Else

           TextBox1.Text = msg

       End If

   End Sub

 

End Class

 

參考資料:

https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation

 

創作者介紹
創作者 iammic 的頭像
iammic

簡單過生活

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