Thread spørgsmål
Hej Eksperter!Jeg sidder lige med et Thread eksempel... som jeg har brug for lidt hjælp til:
Jeg har en textbox og button1 samt button2 på min windows form.
Ved tryk på button1, startes der en ny tråd som skriver noget tekst til tekstboksen med 100 millisek interval.
Det jeg godt vil have hjælp til er, hvordan stopper jeg denne kørende tråd ved tryk på button2, før tråden stopper af sig selv?
Kode:
Imports System.Threading
Public Class ThreadTest
Dim threadCount As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ca As New CounterArgs()
Dim iterations As Integer = 50
ca.Iterations = iterations
ca.StartDelegate = AddressOf Count
Dim t As New Thread(AddressOf ca.StartCounting)
threadCount += 1
t.Name = "Thread " & threadCount.ToString()
Console.WriteLine("Starting thread " & t.Name & " to count " & iterations & " times.")
t.IsBackground = True
t.Start()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'I denne Sub vil jeg gerne kunne stoppe tråden fra Button1_Click
'Hvordan hulen gør jeg det?
End Sub
Private Sub Count(ByVal iterations As Integer)
Dim i As Integer
Dim t As Thread = Thread.CurrentThread
For i = 0 To iterations
If Me.TextBox1.InvokeRequired Then
Me.TextBox1.Invoke(New ChangeTextControlDelegate(AddressOf SetDisplayText), New Object() {t.Name, TextBox1, i.ToString})
Else
Me.SetDisplayText(t.Name, TextBox1, i.ToString)
End If
If Me.TextBox1.InvokeRequired Then
t.Sleep(100)
End If
Next
If Me.TextBox1.InvokeRequired Then
Me.TextBox1.Invoke(New ChangeTextControlDelegate(AddressOf SetDisplayText), New Object() {t.Name, TextBox1, "Ending Thread"})
Else
Me.SetDisplayText(t.Name, TextBox1, "Ending Thread")
End If
End Sub
Public Sub SetDisplayText(ByVal aThreadName As String, ByVal aTextBox As TextBox, ByVal newText As String)
If aTextBox.Text.Length + newText.Length > aTextBox.MaxLength Then
aTextBox.Text = Strings.Right(aTextBox.Text, 1000)
End If
aTextBox.AppendText(aThreadName & ": " & newText & System.Environment.NewLine)
End Sub
Delegate Sub ChangeTextControlDelegate(ByVal aThreadName As String, ByVal aTextBox As TextBox, ByVal newText As String)
Delegate Sub StartCounterDelegate(ByVal iterations As Integer)
Private Class CounterArgs
Public Iterations As Integer
Public StartDelegate As StartCounterDelegate
Public Sub StartCounting()
StartDelegate(Iterations)
End Sub
End Class
End Class