Header menu logo IcedTasks

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:

<PropertyGroup>
  <TargetFramework>net11.0</TargetFramework>
  <LangVersion>preview</LangVersion>
</PropertyGroup>

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

task

Task<'T>

FSharp.Core task

backgroundTask

Task<'T>

FSharp.Core backgroundTask

valueTask

ValueTask<'T>

IcedTasks valueTask

coldTask

unit -> Task<'T>

IcedTasks coldTask

backgroundColdTask

unit -> Task<'T>

IcedTasks backgroundColdTask

cancellableTask

CancellationToken -> Task<'T>

IcedTasks cancellableTask

backgroundCancellableTask

CancellationToken -> Task<'T>

IcedTasks backgroundCancellableTask

cancellableValueTask

CancellationToken -> ValueTask<'T>

IcedTasks cancellableValueTask

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! accepts these values in each builder:

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.

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

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:

namespace System
namespace System.Threading
namespace System.Threading.Tasks
Multiple items
val int: value: 'T -> int (requires member op_Explicit)

--------------------
type int = int32

--------------------
type int<'Measure> = int
Multiple items
val decimal: value: 'T -> decimal (requires member op_Explicit)

--------------------
type decimal = System.Decimal

--------------------
type decimal<'Measure> = decimal
type 'T list = List<'T>
val id: x: 'T -> 'T
namespace System.IO
Multiple items
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
Multiple items
val byte: value: 'T -> byte (requires member op_Explicit)

--------------------
type byte = System.Byte

--------------------
type byte<'Measure> = byte

Type something to start searching.