VB.Net是否有一个暂停的CancellationToken等价物?

时间:2018-01-16 06:12:00

标签: .net vb.net task

我想添加对停止,暂停和恢复任务的支持,所以我想扩展CancellationToken对象并添加一个类似于IsCancellationRequested的标志IsPauseRequested。我无法从CancellationToken继承,那么实现这一目标的最佳方法是什么?

Imports System.Threading

Public Class frmDebugTesting

    Private cts As CancellationTokenSource

    Private Sub StartButton_Click(sender As Object, e As EventArgs) Handles StartButton.Click
        Task.Run(Sub()
                     cts = New CancellationTokenSource
                     Dim foo As New Foo
                     foo.DoWorkA(cts.Token)
                 End Sub)
    End Sub

    Private Sub PauseButton_Click(sender As Object, e As EventArgs) Handles PauseButton.Click
        'cts.Pause()
    End Sub

    Private Sub ResumeButton_Click(sender As Object, e As EventArgs) Handles ResumeButton.Click
        'cts.Resume()
    End Sub

    Private Sub StopButton_Click(sender As Object, e As EventArgs) Handles StopButton.Click
        cts.Cancel()
    End Sub
End Class

Public Class Foo
    Public Sub DoWorkA(ct As Threading.CancellationToken)
        For i = 0 To 100000
            Debug.WriteLine(i)
            'If ct.IsPauseRequested Then
            '    ct.mre.WaitOne()
            'End If
            If ct.IsCancellationRequested Then
                Exit Sub
            End If
        Next
        Dim bar As New Bar
        bar.DoWorkB(ct)
    End Sub
End Class

Public Class Bar
    Public Sub DoWorkB(ct As Threading.CancellationToken)
        For i = 100000 To 0 Step -1
            Debug.WriteLine(i)
            'If ct.IsPauseRequested Then
            '    ct.mre.WaitOne()
            'End If
            If ct.IsCancellationRequested Then
                Exit Sub
            End If
        Next
    End Sub
End Class

0 个答案:

没有答案