Dan*_*iel 7 f# asynchronous task cancellation mailboxprocessor
我试图把它减少到尽可能小的重复,但它仍然有点长,我道歉.
我有一个F#项目引用一个C#项目,代码如下所示.
public static class CSharpClass {
public static async Task AsyncMethod(CancellationToken cancellationToken) {
await Task.Delay(3000);
cancellationToken.ThrowIfCancellationRequested();
}
}
Run Code Online (Sandbox Code Playgroud)
这是F#代码.
type Message =
| Work of CancellationToken
| Quit of AsyncReplyChannel<unit>
let mkAgent() = MailboxProcessor.Start <| fun inbox ->
let rec loop() = async {
let! msg = inbox.TryReceive(250)
match msg with
| Some (Work cancellationToken) ->
let! result =
CSharpClass.AsyncMethod(cancellationToken)
|> Async.AwaitTask
|> Async.Catch
// THIS POINT IS NEVER REACHED AFTER CANCELLATION
match result with
| Choice1Of2 _ -> printfn "Success"
| Choice2Of2 exn -> printfn "Error: %A" exn
return! loop()
| Some (Quit replyChannel) -> replyChannel.Reply()
| None -> return! loop()
}
loop()
[<EntryPoint>]
let main argv =
let agent = mkAgent()
use cts = new CancellationTokenSource()
agent.Post(Work cts.Token)
printfn "Press any to cancel."
System.Console.Read() |> ignore
cts.Cancel()
printfn "Cancelled."
agent.PostAndReply Quit
printfn "Done."
System.Console.Read()
Run Code Online (Sandbox Code Playgroud)
问题是,取消后,控制永远不会返回到异步块.我不确定它是否挂在AwaitTask或Catch.Intuition告诉我在尝试返回上一个同步上下文时它是阻塞的,但我不知道如何确认这一点.我正在寻找关于如何解决这个问题的想法,或者也许在这里有更深入了解的人可以发现问题.
let! result =
Async.FromContinuations(fun (cont, econt, _) ->
let ccont e = econt e
let work = CSharpClass.AsyncMethod(cancellationToken) |> Async.AwaitTask
Async.StartWithContinuations(work, cont, econt, ccont))
|> Async.Catch
Run Code Online (Sandbox Code Playgroud)
最终导致此行为的原因是取消在 F# Async 中很特殊。取消实际上转化为停止和拆除。正如您在源代码中所看到的,取消Task使得它完全脱离了计算。
如果您想要可以在计算中处理的旧产品OperationCanceledException,我们可以自己制作。
type Async =
static member AwaitTaskWithCancellations (task: Task<_>) =
Async.FromContinuations(fun (setResult, setException, setCancelation) ->
task.ContinueWith(fun (t:Task<_>) ->
match t.Status with
| TaskStatus.RanToCompletion -> setResult t.Result
| TaskStatus.Faulted -> setException t.Exception
| TaskStatus.Canceled -> setException <| OperationCanceledException()
| _ -> ()
) |> ignore
)
Run Code Online (Sandbox Code Playgroud)
取消现在只是另一个例外 - 而且是我们可以处理的例外。这是重现:
let tcs = TaskCompletionSource<unit>()
tcs.SetCanceled()
async {
try
let! result = tcs.Task |> Async.AwaitTaskWithCancellations
return result
with
| :? OperationCanceledException ->
printfn "cancelled"
| ex -> printfn "faulted %A" ex
()
} |> Async.RunSynchronously
Run Code Online (Sandbox Code Playgroud)