2011-11-29 19 views
1

如果你有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任務不會在超時時間內完成。

似乎等待只適用於任務,並沒有考慮到鏈,我怎麼能等到「鏈」完成?

+0

爲什麼要考慮鏈條?這不是如何工作的。 –

回答

7

等待ContinueWith函數返回的任務。

+0

ContinueWith返回的任務等待中的問題是,該任務尚未開始,直到正在運行的任務完成。所以它實際上並不等待。必須承認我沒有嘗試過WaitAll,包括這兩個任務,你的想法? – AussieALF

+0

我的意思是存儲繼續任務並在開始初始任務後等待它。您也可以考慮使用更方便的Task.Factory.StartNew,而不是創建新任務並稍後啓動它,因爲它可以避免此類問題。 –