我正在尝试运行异步任务,取消它,然后再次运行它,但是当我第一次取消它时,我再也无法再次运行它了,我做错了什么?。
Private TypeTask As Threading.Tasks.Task
Private TypeTaskCTS As New Threading.CancellationTokenSource
Private TypeTaskCT As Threading.CancellationToken = TypeTaskCTS.Token
Private RequestCancel As Boolean = True
Private Sub TypeWritter(ByVal CancellationToken As Threading.CancellationToken,
ByVal [Text] As String,
ByVal TypeSpeed As Integer,
ByVal PauseSpeed As Integer)
' For each Character in text to type...
For Each c As Char In [Text]
' If not want to cancel then...
If Not CancellationToken.IsCancellationRequested Then
' Type the character.
Console.Write(CStr(c))
' Type-Wait.
Threading.Thread.Sleep(TypeSpeed)
If ".,;:".Contains(c) Then
' Pause-Wait.
Threading.Thread.Sleep(PauseSpeed)
End If
Else ' want to cancel.
' Reset the request cancellation.
RequestCancel = False
' Exit iteration.
Exit For
End If ' CancellationToken.IsCancellationRequested
Next c ' As Char In [Text]
End Sub
Public Sub TypeWritter(ByVal [Text] As String,
Optional ByVal TypeSpeed As Integer = 75,
Optional ByVal PauseSpeed As Integer = 400)
' Run the asynchronous Task.
TypeTask = Threading.Tasks.
Task.Factory.StartNew(Sub()
TypeWritter(TypeTaskCT, [Text], TypeSpeed, PauseSpeed)
End Sub, TypeTaskCT)
' Until Task is not completed or is not cancelled, do...
Do Until TypeTask.IsCompleted OrElse TypeTask.IsCanceled
If RequestCancel Then
If Not TypeTaskCTS.IsCancellationRequested Then
TypeTaskCTS.Cancel
End If
RequestCancel = False
Exit Do
End If
Loop ' TypeTask.IsCompleted OrElse TypeTask.IsCanceled
End Sub
Public Sub TypeWritterLine(ByVal [Text] As String,
Optional ByVal TypeSpeed As Integer = 75,
Optional ByVal PauseSpeed As Integer = 400)
TypeWritter([Text] & vbCrLf, TypeSpeed, PauseSpeed)
Console.WriteLine()
End Sub
注意变量:
Private RequestCancel As Boolean = True
第一次使用时设置为True
取消任务(只是为了更快地测试当我第二次调用Task时会发生什么,我期待错误) 。
我正在尝试的用法是:
Sub Main()
RequestCancel = True ' This should cancel this task:
TypeWritterLine("Some text")
' And this task should run as normally, but it doesn't, I get an empty line:
TypeWritterLine("Some other text")
End Sub
答案 0 :(得分:1)
这是设计的。任务总是执行一次,即使之前没有开始取消。这意味着您必须注意不要多次调用任务的Start方法。 要“重新运行”任务,您必须再次调用Task.Factory.StartNew方法。