簡體   English   中英

Async.Start 與超時和取消令牌?

[英]Async.Start with timeout and cancellationToken?

我有一個要運行的Async<'T>計算,並獲得結果'T

我只有兩個要求:

  1. 在特定timeout:TimeSpan已經過去,我希望計算/IO 被中止。
  2. 我想用一個cancellationToken運行它,以防萬一我想在timeout過去之前中止它。

根據我上面的要求 (1),您可能認為Async.StartChild是一個很好的候選者,因為它接受超時參數,但是,它不接受取消令牌參數!

看來其他的Async. API 中接受取消令牌的方法要么不返回任何內容(因此我無法等待結果),要么僅適用於Async<unit> ,或者不允許我將其與 Async.StartChild 結合以實現我的兩個要求。

另外,我需要在async{}塊中實現它,這意味着在它內部使用Async.RunSynchronously (以防萬一你建議這樣做)會看起來有問題或難看。

我忽略了什么嗎?

謝謝!

正如hvester的評論中提到的,在啟動 Child 計算時不需要傳遞 CancellationToken。 它將由 Parent 共享,並將取消兩者,例如參見此處

let work dueTime = async{
    do! Async.Sleep dueTime
    printfn "Done" }
let workWithTimeOut timeForWork timeOut = async{
    let! comp = Async.StartChild(work timeForWork, timeOut)
    return! comp }

workWithTimeOut 200 400 |> Async.Start // prints "Done"
workWithTimeOut 400 200 |> Async.Start // throws System.TimeoutException

let cts = new System.Threading.CancellationTokenSource()   
Async.Start(workWithTimeOut 400 200, cts.Token)
System.Threading.Thread.Sleep 100
cts.Cancel() // throws System.OperationCanceledException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM