Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/release-notes/.FSharp.Core/11.0.200.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,12 @@
* Correct `FSharpValue.PreComputeTuplePropertyInfo` to report that struct tuples store elements in fields, not properties, and recommend supported tuple readers instead of reporting a valid index as out of range. ([Issue #20801](https://github.com/dotnet/fsharp/issues/20801), [PR #20815](https://github.com/dotnet/fsharp/pull/20815))
* `LeafExpressionConverter` now converts struct tuple patterns such as `let struct (a, b) = t`, reading the elements as fields instead of throwing `ArgumentException`. ([Issue #20884](https://github.com/dotnet/fsharp/issues/20884), [PR #20886](https://github.com/dotnet/fsharp/pull/20886))
* Quotation debug text from `Expr.ToString()`, `Expr.ToString(full)`, and `%A` now prints struct tuple construction as `NewStructTuple`; reference tuples remain `NewTuple`. ([Issue #20800](https://github.com/dotnet/fsharp/issues/20800), [PR #20814](https://github.com/dotnet/fsharp/pull/20814))
* `Async.catch`, `Async.catchWith` propagate `Await`ed cancellation exceptions as per `Task` equivalents. ([PR #21030](https://github.com/dotnet/fsharp/pull/21030))
* `Task.catch`, `Task.catchWith` no longer drop the stacktrace when propagating Cancellation Exceptions. ([PR #21030](https://github.com/dotnet/fsharp/pull/21030))

### Changed

### Breaking Changes

* `Async.catch` (introduced in `11.0.100`) now propagates `Await`ed cancellation exceptions as per `Task` equivalent (it originally yielded an `Error` carrying the Cancellation exception). ([PR #21030](https://github.com/dotnet/fsharp/pull/21030))
* `Async.catchWith` (introduced in `11.0.100`) now propagates `Await`ed cancellation exceptions as per `Task` equivalent (it originally returned passed the Cancellation exception to the supplied `handler`). ([PR #21030](https://github.com/dotnet/fsharp/pull/21030))
20 changes: 9 additions & 11 deletions src/FSharp.Core/async.fs
Original file line number Diff line number Diff line change
Expand Up @@ -2476,22 +2476,20 @@ module Async =

[<CompiledName("CatchWith")>]
let catchWith (handler: exn -> 'T) (computation: Async<'T>) : Async<'T> =
async {
try
return! computation
with e ->
return handler e
}
computation
|> CreateTryWithFilterAsync (function
| :? OperationCanceledException -> None
| e -> async.Return(handler e) |> Some)

[<CompiledName("Catch")>]
let catch (computation: Async<'T>) : Async<Result<'T, exn>> =
async {
try
let! v = computation
return Result.Ok v
with e ->
return Result.Error e
let! v = computation
return Result.Ok v
}
|> CreateTryWithFilterAsync (function
| :? OperationCanceledException -> None
| e -> async.Return(Result.Error e) |> Some)

[<CompiledName("Empty")>]
let empty: Async<unit> = async.Zero()
Expand Down
11 changes: 7 additions & 4 deletions src/FSharp.Core/async.fsi
Original file line number Diff line number Diff line change
Expand Up @@ -2026,9 +2026,10 @@ namespace Microsoft.FSharp.Control

/// <summary>Creates an asynchronous computation that yields the original result on success, or the result of
/// <c>handler exn</c> for non-cancellation exceptions.</summary>
/// <remarks><c>OperationCanceledException</c> and derived types such as <c>TaskCanceledException</c> propagate unchanged,
/// and therefore are never passed to <c>handler</c>.
/// </remarks>
/// <remarks><p><c>OperationCanceledException</c> and derived types such as <c>TaskCanceledException</c> propagate unchanged,
/// and therefore are never passed to <c>handler</c>.</p>
/// <p>In contrast, <c>Async.Catch</c> returns cancellation exceptions raised inside the computation
/// (such as from an awaited canceled <c>Task</c>) as <c>Choice2Of2</c>.</p>
/// <param name="handler">A function to handle (non-cancellation) exceptions, yielding a recovery value based on the exception.
/// Any exception thrown by <c>handler</c> will propagate.</param>
/// <param name="computation">The input computation.</param>
Expand All @@ -2048,7 +2049,9 @@ namespace Microsoft.FSharp.Control

/// <summary>Creates an asynchronous computation that reifies the outcome of the given <c>computation</c> as a <c>Result</c>:
/// <c>Ok</c> on success, <c>Error</c> on failure, so exceptions become values. Cancellation still propagates.</summary>
/// <remarks><c>OperationCanceledException</c> and derived types such as <c>TaskCanceledException</c> propagate unchanged.</remarks>
/// <remarks><p><c>OperationCanceledException</c> and derived types such as <c>TaskCanceledException</c> propagate unchanged.</p>
/// <p>In contrast, <c>Async.Catch</c> returns cancellation exceptions raised inside the computation
/// (such as from an awaited canceled <c>Task</c>) as <c>Choice2Of2</c>.</p></remarks>
/// <param name="computation">The input computation.</param>
/// <returns>An asynchronous computation that yields a <c>Result</c>: <c>Ok</c> with the outcome on success,
/// or <c>Error</c> with the exception on failure.
Expand Down
4 changes: 2 additions & 2 deletions src/FSharp.Core/tasks.fs
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,7 @@ module Task =
try
return! task
with
| :? System.OperationCanceledException as e -> return! raise e
| :? System.OperationCanceledException as e -> return! reraise ()
| e -> return handler e
}

Expand Down Expand Up @@ -948,7 +948,7 @@ module ValueTask =
try
return! task
with
| :? System.OperationCanceledException as e -> return! raise e
| :? System.OperationCanceledException as e -> return! reraise ()
| e -> return handler e
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ let ``Async.map propagates Cancellation (sync)`` () =
let e = Assert.Throws<OperationCanceledException>(fun () -> a |> asyncWaitWithCt ct |> ignore)
Assert.Equal(ct, e.CancellationToken)

[<Fact>]
let ``Async.map propagates return! Cancellation as TaskCanceledException (sync)`` () =
let a = async { return! Async.Await(Task.FromCanceled<int>(CancellationToken(true))) }
Assert.Throws<TaskCanceledException>(fun () -> Async.map id a |> Async.RunSynchronouslyImmediate :> obj) |> ignore

[<Fact>]
let ``Async.map propagates Cancellation (async)`` () =
let mutable mapperWasCalled = false
Expand Down Expand Up @@ -93,6 +98,11 @@ let ``Async.bind propagates Cancellation (sync)`` () =
let e = Assert.Throws<OperationCanceledException>(fun () -> a |> asyncWaitWithCt ct |> ignore)
Assert.Equal(ct, e.CancellationToken)

[<Fact>]
let ``Async.bind propagates return! Cancellation as TaskCanceledException (sync)`` () =
let a = async { return! Async.Await(Task.FromCanceled<int>(CancellationToken(true))) }
Assert.Throws<TaskCanceledException>(fun () -> Async.bind Async.result a |> Async.RunSynchronouslyImmediate :> obj) |> ignore

[<Fact>]
let ``Async.bind propagates Cancellation (async)`` () =
let cts = new CancellationTokenSource()
Expand Down Expand Up @@ -140,6 +150,11 @@ let ``Async.ignore propagates Cancellation (sync)`` () =
let e = Assert.Throws<OperationCanceledException>(fun () -> a |> asyncWaitWithCt ct)
Assert.Equal(ct, e.CancellationToken)

[<Fact>]
let ``Async.ignore propagates return! Cancellation as TaskCanceledException (sync)`` () =
let a = async { return! Async.Await(Task.FromCanceled<int>(CancellationToken(true))) }
Assert.Throws<TaskCanceledException>(fun () -> Async.ignore<int> a |> Async.RunSynchronouslyImmediate :> obj) |> ignore

[<Fact>]
let ``Async.ignore propagates Cancellation (async)`` () =
let mutable cancellationFailed = false
Expand All @@ -154,6 +169,25 @@ let ``Async.ignore propagates Cancellation (async)`` () =
let e = Assert.ThrowsAsync<TaskCanceledException>(fun () -> t).Result
Assert.NotEqual(cts.Token, e.CancellationToken)
Assert.False cancellationFailed


let cancelledAsync<'T> : Async<'T> =
Async.FromContinuations(fun (_, _, cancel) ->
cancel (OperationCanceledException()))

// In contrast to Task.catch+catchWith (and Async.catch/catchWith after it was corrected post 11.0.101), Async.Catch *will* trap a Canceled awaited Task
[<Fact>]
let ``Async.Catch treats Task Cancellation as Choice2Of2`` () =
let a = async { return! Async.Await(Task.FromCanceled(CancellationToken(true))) }
let res = Async.Catch a |> Async.RunSynchronouslyImmediate
match res with
| Choice2Of2 e -> Assert.IsType<TaskCanceledException> e
| Choice1Of2 () -> failwith "unexpected success"

[<Fact>]
let ``Async.Catch treats Canceled Async as OperationCanceledException (sync)`` () =
let a = cancelledAsync<int>
Assert.Throws<OperationCanceledException>(fun () -> Async.Catch a |> Async.RunSynchronouslyImmediate :> obj) |> ignore

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this async really cancelled? There is no cancellation token?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. The minute you run it, it cancels itself, independent of a controlling ambient CT and./or a sibling or Async.Parallel etc doing it:

let cancelledAsync<'T> : Async<'T> =
    Async.FromContinuations(fun (_, _, cancel) ->
        cancel (OperationCanceledException()))



[<Fact>]
Expand Down Expand Up @@ -185,6 +219,11 @@ let ``Async.catchWith recovers from exception (async)`` () = async {
let! result = a
Assert.Equal(-1, result) }

[<Fact>]
let ``Async.catchWith propagates Canceled Async as OperationCanceledException (sync)`` () =
let a = cancelledAsync<int>
Assert.Throws<OperationCanceledException>(fun () -> Async.catchWith (fun _ -> -1) a |> Async.RunSynchronouslyImmediate :> obj) |> ignore

[<Fact>]
let ``Async.catchWith propagates Cancellation (sync)`` () =
let mutable cancellationFailed = false
Expand All @@ -211,6 +250,11 @@ let ``Async.catchWith propagates Cancellation (async)`` () =
let e = Assert.ThrowsAsync<TaskCanceledException>(fun () -> t).Result
Assert.NotEqual(cts.Token, e.CancellationToken)

// Aligns with Task, deviates from Async.Catch and 11.0.101
[<Fact>]
let ``Async.catchWith propagates return! Cancellation as TaskCanceledException (sync)`` () =
let a = async { return! Async.Await (Task.FromCanceled<int>(CancellationToken(true))) }
Assert.Throws<TaskCanceledException>(fun () -> Async.catchWith (fun _ -> -1) a |> Async.RunSynchronouslyImmediate :> obj) |> ignore

[<Fact>]
let ``Async.catch returns Ok on success (sync)`` () =
Expand Down Expand Up @@ -246,6 +290,17 @@ let ``Async.catch propagates Cancellation (sync)`` () =
let e = Assert.Throws<OperationCanceledException>(fun () -> a |> asyncWaitWithCt ct |> ignore)
Assert.Equal(ct, e.CancellationToken)

// Aligns with Task, deviates from Async.Catch and 11.0.101
[<Fact>]
let ``Async.catch propagates return! Cancellation as TaskCanceledException (sync)`` () =
let a = async { return! Async.Await(Task.FromCanceled<int>(CancellationToken(true))) }
Assert.Throws<TaskCanceledException>(fun () -> Async.catch a |> Async.RunSynchronouslyImmediate :> obj) |> ignore

[<Fact>]
let ``Async.catch propagates Canceled Async as OperationCanceledException (sync)`` () =
let a = cancelledAsync<int>
Assert.Throws<OperationCanceledException>(fun () -> Async.catch a |> Async.RunSynchronouslyImmediate :> obj) |> ignore

[<Fact>]
let ``Async.catch propagates Cancellation (async)`` () =
let cts = new CancellationTokenSource()
Expand Down Expand Up @@ -311,7 +366,7 @@ let ``Async.parallelLimit limits concurrency`` () =
if concurrent > maxConcurrent then maxConcurrent <- concurrent
concurrent)
do! Async.Sleep 1
lock lockObj (fun () -> concurrent <- concurrent - 1) |> ignore
lock lockObj (fun () -> concurrent <- concurrent - 1)
return n
}]
|> Async.parallelLimit 3
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,14 @@ module TaskModuleFunctionsTests =
Assert.Equal(ct, e.CancellationToken)
Assert.True t.IsCanceled

[<Fact>]
let ``Task.catchWith propagates return! Cancellation (sync)`` () =
let ct = CancellationToken true
let t = task { return! Task.FromCanceled<int>(ct) } |> Task.catchWith (fun _ -> -1)
let e = Assert.ThrowsAsync<TaskCanceledException>(fun () -> t).Result
Assert.Equal(ct, e.CancellationToken)
Assert.True t.IsCanceled

[<Fact>]
let ``Task.catchWith propagates Cancellation (async)`` () =
let tcs = TaskCompletionSource<int>()
Expand Down Expand Up @@ -310,6 +318,14 @@ module TaskModuleFunctionsTests =
Assert.Equal(ct, e.CancellationToken)
Assert.True t.IsCanceled

[<Fact>]
let ``Task.catch propagates return! Cancellation (sync)`` () =
let ct = CancellationToken true
let t = task { return! Task.FromCanceled<int>(ct) } |> Task.catch
let e = Assert.ThrowsAsync<TaskCanceledException>(fun () -> t).Result
Assert.Equal(ct, e.CancellationToken)
Assert.True t.IsCanceled

[<Fact>]
let ``Task.catch propagates cancellation (async)`` () =
let tcs = TaskCompletionSource<int>()
Expand Down
Loading