簡體   English   中英

F#處理任務取消

[英]F# handling Task cancellation

我正在努力理解為什么某些代碼從未執行過。

考慮以下擴展方法:

type WebSocketListener with
  member x.AsyncAcceptWebSocket = async {
    try
        let! client = Async.AwaitTask <| x.AcceptWebSocketAsync Async.DefaultCancellationToken
        if(not (isNull client)) then
            return Some client
        else
            return None
    with
        | :? System.Threading.Tasks.TaskCanceledException -> 
        | :? AggregateException ->
            return None
  }

我知道取消標記被取消時, AcceptSocketAsync引發TaskCanceledException 我已經簽入了C#應用程序。 這個想法是返回None

但是,那永遠不會發生。 如果我在最后一個return None甚至在if表達式中都設置了一個斷點,則在取消標記被取消后,它永遠不會停在那里。 而且我知道它正在Async.AwaitTask等待,因為如果在取消之前,其他客戶端已連接,則它將起作用,並且它將在斷點處停止。

我有點迷茫,為什么例外迷失了?

取消使用F#異步中的特殊路徑-Async.AwaitTask會將已取消任務的執行重新路由到取消繼續。 如果您想要其他行為-您始終可以手動執行以下操作:

type WebSocketListener with
  member x.AsyncAcceptWebSocket = async {
    let! ct = Async.CancellationToken
    return! Async.FromContinuations(fun (s, e, c) ->
        x.AcceptWebSocketAsync(ct).ContinueWith(fun (t: System.Threading.Tasks.Task<_>) -> 
            if t.IsFaulted then e t.Exception
            elif t.IsCanceled then s None // take success path in case of cancellation
            else 
            match t.Result with
            | null -> s None
            | x -> s (Some x)
        )
        |> ignore
    )
  }

暫無
暫無

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

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