我很难理解为什么有些代码从未被执行过。
考虑一下这种扩展方法:
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中,因为如果在取消之前,其他客户端连接,它工作,它停止在断点。
我有点迷茫,为什么例外会丢失呢?
发布于 2014-11-18 02:48:50
取消使用一个特殊的路径在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
)
}https://stackoverflow.com/questions/26984546
复制相似问题