Reputation: 20464
I'm trying to run an asynchronous task, cancel it, and run it again, but when I cancel it for first time I'm not able anymore to run it again, what I'm doing wrong?.
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
Notice the variable:
Private RequestCancel As Boolean = True
Which is set to True
to cancel the task when used for first time (just for make things faster to test what happens when I try to call the Task a second time, where I'm expecting the error).
The usage that I'm trying is this:
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
Upvotes: 0
Views: 161
Reputation: 2786
This is by design. A task is always executed once, even if not begin canceled before. This means that you must pay attention to not call a task's Start method multiple times. For "rerunning" a task you will have to call the Task.Factory.StartNew method again.
Upvotes: 1