.net 无法重新运行已取消的任务
我试图运行一个异步任务,取消它,然后再次运行它,但是当我第一次取消它时,我再也不能运行它了,我做错了什么.net 无法重新运行已取消的任务,.net,vb.net,multithreading,asynchronous,task,.net,Vb.net,Multithreading,Asynchronous,Task,我试图运行一个异步任务,取消它,然后再次运行它,但是当我第一次取消它时,我再也不能运行它了,我做错了什么 Private TypeTask As Threading.Tasks.Task Private TypeTaskCTS As New Threading.CancellationTokenSource Private TypeTaskCT As Threading.CancellationToken = TypeTaskCTS.Token Private RequestCancel As
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
以在第一次使用时取消任务(只是为了更快地测试当我尝试第二次调用该任务时发生的情况,我预计会出现错误)
我尝试的用法是:
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
这是故意的。任务始终执行一次,即使之前没有开始或取消。这意味着您必须注意不要多次调用任务的Start方法。
对于“重新运行”任务,您必须再次调用task.Factory.StartNew方法。
对于“重新运行”任务,您必须再次调用task.Factory.StartNew方法。
是的,但我认为每次调用该方法时,我的代码中已经在做这些了<代码>类型任务=Threading.Tasks.Task.Factory.StartNew(Sub()…我创建了一个简单的示例,它多次启动一些任务。执行良好后,我尝试运行您的代码。执行此操作时,我注意到您始终使用同一个cancellationToken实例。第一次取消任务时,此令牌将记住已请求取消,并且不会执行其他任务ute。确保您使用了CancellationTokenSource和CancellationToken的新实例。然后它将正常工作。