2013年3月6日 星期三

vb.net thread 暫停-研究(2)

參考來源:Thread.Suspend()已过时...多线程
參考MSDN:Thread.Interrupt 方法
--
 

Imports System.Threading

Public Class Form1

    Dim paused As Boolean
    Dim resumeEvent As ManualResetEvent = New ManualResetEvent(False) '另外用法(暫停)

    '--
    Dim t As Thread
    Dim st As ThreadStart
    Dim count As Integer

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

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

        st = New ThreadStart(AddressOf  countFunction )
        t = New Thread(st)

        MessageBox.Show("建立")
    End Sub

    Private Sub countFunction()
        While True
            count = (count + 1)
            If paused Then
                resumeEvent.WaitOne()
            End If
            If count > 10000 Then
                count = 0
            End If
        End While
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Try
            t.Start()
            MessageBox.Show("啟動")
        Catch ex As Exception
        End Try
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Try          
            t.Abort()
            t.Join()
            MessageBox.Show(("停止,累計: " + count.ToString))
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        Try
            t.Suspend()
            MessageBox.Show(("暫停,累計: " + count.ToString))
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        Try
            t.Resume()
            MessageBox.Show("繼續")
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        Try
            resumeEvent.Reset()
            paused = True
            MessageBox.Show(("暫停 p 版,累計: " + count.ToString))
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
        Try
            paused = False
            resumeEvent.Set()
            MessageBox.Show("繼續 p 版")
        Catch ex As Exception

        End Try
    End Sub
End Class

沒有留言:

張貼留言