VB.Net กับ Thread
หากต้องการทำงานแล้วแสดงผลให้ User บนหน้าจอแล้วละก็ Thread เป็นทางเลือกนึงครับ
ดังตัวอย่าง
Imports System.Threading
Public boolStop As Boolean = False
ปุ่มนี้ไว้เรียก Run
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim t as Thread
t = New Thread(AddressOf Me.TestLoop)
t.IsBackground = True
boolStop = False
t.Start()
End Sub
ปุ่มนี้ไว้หยุดทำงาน
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
boolStop = True
End Sub
ทีนี้ก็บนหน้าจอก็วางปุ่มไว้สองปุ่ม ปุ่มนึงไว้ Start Testloop อีกปุ่มไว้หยุด Testloop แล้วก็วาง ListBox ไว้ 1 ตัวเพื่อแสดงการทำงานครับ
โค้ด TestLoop เป็นดังนี้
Private Sub TestLoop()
Dim i As Integer = 1
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf TestLoop))
Else
ListBox1.Items.Clear()
Do While Not boolStop
ListBox1.Items.Add("Iteration: " & CStr(i))
i += 1
ListBox1.SelectedIndex = ListBox1.Items.Count - 1
'Thread.CurrentThread.Sleep(10)
Application.DoEvents()
Loop
End If
End Sub
ดังตัวอย่าง
Imports System.Threading
Public boolStop As Boolean = False
ปุ่มนี้ไว้เรียก Run
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim t as Thread
t = New Thread(AddressOf Me.TestLoop)
t.IsBackground = True
boolStop = False
t.Start()
End Sub
ปุ่มนี้ไว้หยุดทำงาน
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
boolStop = True
End Sub
ทีนี้ก็บนหน้าจอก็วางปุ่มไว้สองปุ่ม ปุ่มนึงไว้ Start Testloop อีกปุ่มไว้หยุด Testloop แล้วก็วาง ListBox ไว้ 1 ตัวเพื่อแสดงการทำงานครับ
โค้ด TestLoop เป็นดังนี้
Private Sub TestLoop()
Dim i As Integer = 1
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf TestLoop))
Else
ListBox1.Items.Clear()
Do While Not boolStop
ListBox1.Items.Add("Iteration: " & CStr(i))
i += 1
ListBox1.SelectedIndex = ListBox1.Items.Count - 1
'Thread.CurrentThread.Sleep(10)
Application.DoEvents()
Loop
End If
End Sub
Comments