如果你有Task.Wait()不包括任何鏈接(ContinueWith)任務
Private Shared Sub msg(Optional message As String = "")
Debug.WriteLine(Threading.Thread.CurrentThread.ManagedThreadId & " " & message)
End Sub
<TestMethod()>
Public Sub TestMethod1()
Dim cancel As New Threading.CancellationTokenSource
msg("starting")
Dim start As DateTime = DateTime.Now
Dim task As New Task(Sub()
msg("in thread")
Do Until Now.Subtract(start).TotalMilliseconds > 2000
Threading.Thread.Sleep(500)
msg("loop")
cancel.Token.ThrowIfCancellationRequested()
Loop
End Sub, cancel.Token, TaskCreationOptions.LongRunning)
task.ContinueWith(Sub(result As task)
msg("Continue task running")
Debug.WriteLine(result.Status.ToString & If(result.Exception Is Nothing, ", no exception", ", exception occurred " & result.Exception.GetType.Name))
Do Until Now.Subtract(start).TotalMilliseconds > 10000
cancel.Token.ThrowIfCancellationRequested()
Threading.Thread.Sleep(500)
msg("innerloop")
Loop
End Sub)
task.Start()
Try
If Not task.Wait(4000, cancel.Token) Then
msg("wait expired, time to cancel)")
cancel.Cancel()
End If
task.Wait()
Catch ex As OperationCanceledException
msg("task was cancelled")
Finally
msg("finishing")
End Try
End Sub
的問題是,當我做task.Wait(4000,cancel.Token)這應該最終失敗的ContinueWith任務不會在超時時間內完成。
似乎等待只適用於任務,並沒有考慮到鏈,我怎麼能等到「鏈」完成?
爲什麼要考慮鏈條?這不是如何工作的。 –