Runtime-async task builders
.NET 11 adds runtime async. In a runtime-async method, the .NET runtime suspends and resumes the method. The compiler does not generate a state machine for the method.
F# 11 has preview support for runtime async. IcedTasks uses this support in the builders of the IcedTasks.Polyfill.RuntimeTask namespace. For the steps to use them, see Use the runtime-async task builders.
Requirements
A project that uses these builders must:
- Target
net11.0or later. - Use the .NET 11 SDK.
- Set
LangVersiontopreview. - Run on a .NET 11 or later runtime.
|
If LangVersion is not preview, the compiler stops with error FS3350: Feature 'runtime async' is not available in F# 11.0.
Runtime async is a preview feature of F# 11. A later F# compiler can change the requirements or the behavior.
Each net11.0 project that references IcedTasks gets the net11.0 build, also when it does not use these builders. That build depends on FSharp.Core 11.0.101 or later.
The namespace contains the builders only in the net11.0 build of IcedTasks. In the builds for older target frameworks, the namespace is empty. Thus, in a project that targets net10.0, each builder name gives the state-machine builder, also when the project opens the namespace.
The builders
When you open the namespace, these builders replace the builders with the same names. The result types do not change, so the companion modules, such as CancellableTask.map, continue to work.
Builder |
Result |
Replaces |
|---|---|---|
|
|
FSharp.Core |
|
|
FSharp.Core |
|
|
IcedTasks |
|
|
IcedTasks |
|
|
IcedTasks |
|
|
IcedTasks |
|
|
IcedTasks |
|
|
IcedTasks |
module Orders =
open System.Threading
open System.Threading.Tasks
open IcedTasks.Polyfill.RuntimeTask
let getTotal (getPrice: int -> CancellationToken -> Task<decimal>) (ids: int list) =
cancellableTask {
let mutable total = 0m
for id in ids do
let! price = getPrice id
total <- total + price
return total
}
The cold and cancellable builders return a function. Each call of the function runs the computation again, as a new runtime-async method.
The background* builders start the computation on the thread pool when the caller has a SynchronizationContext or a task scheduler that is not the default. Otherwise, they start the computation on the caller thread.
Supported expressions
The builders support:
let!,do!,return!, andand!.useanduse!forIDisposableandIAsyncDisposablevalues.foroverseq<'T>andIAsyncEnumerable<'T>.while,try/with,try/finally, andif.
let! accepts these values in each builder:
Task<'T>,Task,ValueTask<'T>, andValueTask.Async<'T>.-
A cold task, a cold awaitable, or a function that returns an awaiter, for example
unit -> Task<'T>,unit -> ValueTask, orunit -> TaskAwaiter<'T>. If a function returns a type that is both an awaitable and an awaiter, the builder calls itsGetAwaitermethod and awaits the result, as the state-machine builders do. - An awaiter or an awaitable value, such as the result of
Task.Yield().
The cancellable builders also accept a CancellationToken -> 'Awaitable or a CancellationToken -> 'Awaiter value, for example a CancellableTask<'T>, a CancellableValueTask<'T>, or a CancellationToken -> TaskAwaiter<'T> function.
The builders await a Task or a ValueTask that an operand gives with AsyncHelpers.Await, and other awaiters with AsyncHelpers.UnsafeAwaitAwaiter. In the cancellable builders, a CancellationToken -> 'Awaitable value, a cold task, and an Async give an awaiter, so these builders await them with AsyncHelpers.UnsafeAwaitAwaiter.
Cancellation in the cancellable builders
The cancellable builders keep the CancellationToken that the caller gives. This token is the ambient token.
- If the token is cancelled when the caller calls the function, the function returns a cancelled task, and the computation does not run.
- The builder checks the token before each
let!,do!,return!, andand!, and before eachMoveNextAsynccall and before the body inforover anIAsyncEnumerable<'T>. If the token is cancelled, the builder throwsOperationCanceledException, and the task is cancelled. - The builder gives the token to each bound
CancellationToken -> 'Awaitablevalue,CancellationToken -> 'Awaiterfunction, andAsync<'T>value, and toGetAsyncEnumeratorinforover anIAsyncEnumerable<'T>. It calls a function after the check. - Cancellation stops the computation only at a check or in an operation that uses the token. Code between two checks continues to run.
- In
forover anIAsyncEnumerable<'T>, the builder always awaits a startedMoveNextAsyncbefore it disposes the enumerator, as C#await foreachdoes. A move that does not use the token delays the cancellation until the move completes. - The builder does not check the token before
DisposeAsync,Dispose, or afinallyblock. Thus, cleanup runs also after cancellation. returnandforover aseq<'T>do not check the token.
To get the ambient token in the computation, bind CancellableTask.getCancellationToken ():
let writeAll (stream: System.IO.Stream) (chunks: byte[] list) =
cancellableTask {
let! ct = CancellableTask.getCancellationToken ()
for chunk in chunks do
do! stream.WriteAsync(chunk, ct)
}
Start order of and! operands
The builders do not start a task or a value task that an operand gives. They await the task in the state that the task has. Thus, a task that was created and not started stays incomplete until other code starts it. An awaiter or an awaitable that starts its work only when the builder registers a continuation does not start until the builder awaits it.
The non-cancellable builders evaluate all and! operands from left to right before they await the first operand. An Async, a cold task, and a cold awaitable start when the builder evaluates them. If the evaluation of an operand throws, that exception is the result, and the builder does not await the operands.
The cancellable builders start a cancellable operand, an Async, and a cold task when they bind it, with the ambient token. For and!, they start these operands from left to right, and then they await all operands from left to right. If the start of an operand throws, the builder does not start the operands to its right, and the exception is the result. The builders check the token before they await each operand. These rules are the same as in the state-machine cancellable builders.
When the builder awaits the operands, it awaits them from left to right. If an operand fails, the builder does not await the operands to its right, and the result has the exception of that operand. The operands to its right can continue to run. The builder does not read the result of an operand to the right of a failed operand.
F# combines three or more operands from the right. Thus, let! a = x and! b = y and! c = z combines x with the pair of y and z. The non-cancellable runtime builders await x, then y, then z. The cancellable builders run the inner pair as one operation, and they start that operation with x. In the cancellable builders, the inner pair can read the results of y and z before x completes, and an exception in y or z waits until the builder awaits the inner pair. The state-machine cancellable builders behave the same way.
Differences from the state-machine builders
- The F# compiler must inline all of the builder members into the method that contains the computation expression. Each member has
NoDynamicInvocation, so a call to a member through reflection throwsTargetInvocationExceptionwith aNotSupportedExceptioninside it. - The body of a runtime-async method is small, so the F# optimizer can inline a small function that uses the builder into its caller. If you must see the function name in stack traces, put
[<MethodImpl(MethodImplOptions.NoInlining)>]on the function. - The F# compiler gives generated names to the methods that contain the body, such as
func1@12.Invoke. Stack traces show these names. - The
background*builders examine theSynchronizationContextand the task scheduler when the caller calls the function or starts the task. The state-machinebackgroundColdTaskandbackgroundCancellableTaskexamine them when the computation expression makes the function. - The runtime-async
coldTaskandbackgroundColdTaskcall a bound cold task when they evaluate it. The state-machinecoldTaskcalls it at the bind. This changes the order of side effects inlet! a = coldLeft and! b = hotRight (). - In
forover anIAsyncEnumerable<'T>, the state-machine cancellable builders check the token between theMoveNextAsynccall and its await. If the move cancels the token, they dispose the enumerator while the move is pending. A C# async iterator rejects that withNotSupportedException. The runtime builders await the move first. - The F# compiler issue dotnet/fsharp#20869 is open. It reports that a rethrow after a suspending
withhandler orfinallyblock can lose the stack trace.useandforover anIAsyncEnumerable<'T>awaitDisposeAsyncoutside the protected region, so they keep the stack trace. Awithhandler in your own code that suspends and then rethrows can lose it.
Builders that have no runtime-async version
taskUnit, backgroundTaskUnit, valueTaskUnit, the pooling builders, asyncEx, and parallelAsync have no runtime-async version. The vTask alias continues to give the state-machine valueTask builder.
Related:
- Use the runtime-async task builders
- Polyfill namespaces and shadowing
- Choosing a builder
- Runtime-async specification
val int: value: 'T -> int (requires member op_Explicit)
--------------------
type int = int32
--------------------
type int<'Measure> = int
val decimal: value: 'T -> decimal (requires member op_Explicit)
--------------------
type decimal = System.Decimal
--------------------
type decimal<'Measure> = decimal
type Stream = inherit MarshalByRefObject interface IAsyncDisposable interface IDisposable member BeginRead: buffer: byte array * offset: int * count: int * callback: AsyncCallback * state: obj -> IAsyncResult member BeginWrite: buffer: byte array * offset: int * count: int * callback: AsyncCallback * state: obj -> IAsyncResult member Close: unit -> unit member CopyTo: destination: Stream -> unit + 1 overload member CopyToAsync: destination: Stream -> Task + 3 overloads member Dispose: unit -> unit member DisposeAsync: unit -> ValueTask ...
<summary>Provides a generic view of a sequence of bytes. This is an abstract class.</summary>
--------------------
System.IO.Stream() : System.IO.Stream
val byte: value: 'T -> byte (requires member op_Explicit)
--------------------
type byte = System.Byte
--------------------
type byte<'Measure> = byte
IcedTasks