Skip to content

Add a native valueTask { } computation expression to FSharp.Core #1474

Open

Description

@xperiandri

I propose we add a valueTask { } computation expression to FSharp.Core: a resumable-code builder over AsyncValueTaskMethodBuilder<'T> / AsyncValueTaskMethodBuilder, producing ValueTask<'T> and ValueTask, shaped exactly like the existing task { } and available on the netstandard2.1 and net* target frameworks.

This re-raises #1244, closed as Not Planned on 2024-06-12, together with its implementation dotnet/fsharp#14755. I want to be precise about what has and has not changed since, because #1244 was closed for two distinct reasons.

The dependency objection is unchanged, and this proposal does not ask you to move on it. FSharp.Core still takes no dependency on System.Threading.Tasks.Extensions, so AsyncValueTaskMethodBuilder remains unavailable on netstandard2.0 and the builder cannot ship there. That is accepted here as a constraint, not contested.

The closing reason was the second one — "until we have a better story for such big differences in the public surface area for different targets". What has changed there is precedent rather than written policy, and it is worth weighing honestly:

  • FSharp.Core 11 shipped the ValueTask module (result, map, bind, ignore, catchWith, catch, empty, ofTask) and Task.ofValueTask (#1466, PR #19844), Async.Await overloads for ValueTask/ValueTask<'T> (#840, PR #19785) and Async.StartTaskImmediate overloads for the same (#1284, PR #20258) — all under #if NETSTANDARD2_1 || NET, all with no new dependency, all merged in August 2026.
  • In review, the resulting TFM divergence was treated as routine: the one comment it drew was a request to regenerate the four FSharp.Core.SurfaceArea.netstandard2{0,1}.{debug,release}.bsl baselines. The baselines now record the split as a reviewed artifact — no ValueTask entries on netstandard2.0, fourteen on netstandard2.1, eighteen on netcore.
  • But nobody wrote the story down. There is no documented policy in docs/, in fsharp-core-notes.md or in an issue that a proposal like this one can point at and say "this is covered". If the team's position is that the policy has to be written before another TFM-conditional API lands, that is a fair answer, and I would rather help draft it than argue the point.

What is genuinely different about this particular API, and what was not said in #1244:

  • On netstandard2.0 FSharp.Core cannot so much as name ValueTask. Nothing regresses and the divergence does not widen in a new direction — it lands in the same place the existing ValueTask surface already lives.
  • Consuming a ValueTask in task { } already works on every target framework, because LowPriority.Bind<^TaskLike, …> is structural SRTP over GetAwaiter and is resolved in the consumer's compilation, not in FSharp.Core's. Only producing one needs the builder. So what is missing on netstandard2.0 is a single builder value, not — in the words of Support for ValueTask state machine computation expression #1244's first comment — a "whole chunk of API". The asymmetry is the real argument: F# already awaits ValueTask everywhere and cannot return one anywhere.

The existing way of approaching this problem in F# is to write task { … } and wrap the result:

member this.ReadAsync(buffer) : ValueTask<int> =
    task {
        if cached.Length > 0 then return cached.Length      // synchronous path, still allocates a Task
        else return! this.SlowPath(buffer)
    }
    |> ValueTask<int>

which allocates on every call the Task that ValueTask exists to avoid, defeating the point of returning one. The alternative is a third-party builder — IcedTasks has valueTask, poolingValueTask and cancellableValueTask, and was cited in #1244's own closure as the reason to decline.

Pros and Cons

The advantages of making this adjustment to F# are

  • A computation that completes synchronously allocates nothing. That is the entire reason ValueTask exists, and F# currently cannot express it.
  • Implementing a ValueTask-returning interface member is routine in modern .NET — IAsyncDisposable.DisposeAsync, IAsyncEnumerator.MoveNextAsync, IValueTaskSource<'T>, and large parts of ASP.NET Core, Roslyn, ServiceHub and the VS SDK. Today every one of those forces the wrap above, so F# code implementing a hot-path .NET interface is structurally slower than the C# it is talking to.
  • Parity with C# async ValueTask / async ValueTask<T>, available since C# 7.
  • It completes a story FSharp.Core has now half-shipped: the ValueTask module, Async.Await and Async.StartTaskImmediate all handle ValueTask, but nothing in the language produces one.
  • An implementation already exists: PR #14755 by @thinkbeforecoding, closed only because the suggestion was.

The disadvantages of making this adjustment to F# are

  • The public surface differs between netstandard2.0 and the other target frameworks. Already true of every ValueTask API in FSharp.Core 11 and already recorded per TFM in the surface-area baselines — but it is one more thing a netstandard2.0 consumer will not find, and, unlike a missing function, a missing builder is discovered as a syntax-level failure rather than a missing name.
  • A second builder largely parallel to TaskBuilder, with the attendant risk of the two drifting. The resumable-code scaffolding should be shared rather than copied.
  • ValueTask may be awaited only once and must not be awaited after .AsTask(). A builder makes it easy to produce them, and therefore easy to misuse them. This needs to be prominent in the documentation; C# has the same hazard and documents it the same way.
  • Open design question: whether to also expose poolingValueTask { } over PoolingAsyncValueTaskMethodBuilder (net6+), which trades pooled state machines for an allocation on the asynchronous path. It narrows the surface further by TFM, so it is probably a follow-up rather than part of this.

Extra information

Estimated cost (XS, S, M, L, XL, XXL): M — PR #14755 is an existing implementation needing a rebase, a surface-area baseline update for netstandard2.1/netcore only, and tests.

Related suggestions:

  • #1244 — the same request, closed Not Planned; this re-raises it
  • #581 — native task { }, the template this follows
  • #1466, #1284, #840 — the shipped ValueTask APIs discussed above
  • #866 — DisposeAsync in async, which needs the same ValueTask plumbing
  • #1459 — syncTask, another proposed builder in the same family

Affidavit (please submit!)

Please tick these items by placing a cross in the box:

Please tick all that apply:

  • This is not a breaking change to the F# language design
  • I or my company would be willing to help implement and/or test this

For Readers

If you would like to see this issue implemented, please click the 👍 emoji on this issue. These counts are used to generally order the suggestions by engagement.

Activity

  1. T-Gro commented on Sep 21, 2026

    @T-Gro
    Contributor

    As of now (net11), I see more value in focusing on runtime async. Many uses of Task get optimized away by the runtime and there is no additional allocation anymore.

    More specifically, I would not want to introduce a new F#-resumable-code builder now.

    We can certainly leave this open and wait for some benchmarks around scenarios with runtime async that show a clear benefit. The F# recognized primitives for runtime async work with ValueTask as well.

  2. davidglassborow commented on Sep 21, 2026

    @davidglassborow

    @T-Gro is runtime async support in F# being tracked somewhere ? Presumably F# Task code won't currently take advantage of the new opt in .net11 features ?

  3. vzarytovskii commented on Sep 21, 2026

    @vzarytovskii

    One question to ask when theres a suggestion to add something to fslib - why does it have to be in core library and can't be something like IcedTasks?

  4. xperiandri commented on Sep 21, 2026

    @xperiandri
    Author

    Should be in core lib, my mistake

  5. vzarytovskii commented on Sep 21, 2026

    @vzarytovskii

    Should be in core lib, my mistake

    Yeah, I get that. I'm just curious about reasoning on why.

  6. T-Gro commented on Sep 21, 2026

    @T-Gro
    Contributor

    @T-Gro is runtime async support in F# being tracked somewhere ? Presumably F# Task code won't currently take advantage of the new opt in .net11 features ?

    @davidglassborow : net11 F# compiler comes equipped with the necessary compiler-recognized primitives and we do have a prototype of the builder, which people can copy to their projects or host in a 3rd party package. It is not replacing the built-in task{} for now in any way.

  7. davidglassborow commented on Sep 21, 2026

    @davidglassborow

    @davidglassborow : net11 F# compiler comes equipped with the necessary compiler-recognized primitives and we do have a prototype of the builder, which people can copy to their projects or host in a 3rd party package. It is not replacing the built-in task{} for now in any way.

    See dotnet/fsharp#20235 for more details

  8. charlesroddie commented on Sep 22, 2026

    @charlesroddie

    Wow it's huge that F# is getting runtime async. Is the syntax for this ironed out? The PR doc https://github.com/dotnet/fsharp/pull/20235/changes#diff-1016087f2b2c5383cc3f16d68b905f0e24f87acad94712072b7730f089774f4dR252 suggests that enabling the preview doesn't immediately use the feature in existing async/task but instead is the currently scaffolding on which users can build async/task replacements?

  9. davidglassborow commented on Sep 23, 2026

    @davidglassborow

    Wow it's huge that F# is getting runtime async. Is the syntax for this ironed out? The PR doc https://github.com/dotnet/fsharp/pull/20235/changes#diff-1016087f2b2c5383cc3f16d68b905f0e24f87acad94712072b7730f089774f4dR252 suggests that enabling the preview doesn't immediately use the feature in existing async/task but instead is the currently scaffolding on which users can build async/task replacements?

    That's my reading of it, that new bulders outside of FSharp.Core can be written to allow runtime async, starting from the prototype

  10. T-Gro commented on Sep 23, 2026

    @T-Gro
    Contributor

    @charlesroddie :

    Yes, the work which has landed is just enablement for it, not changing existing builder.

    Eventually, I would want to to just fuse with the task{} builder. However, for an interims period, we might need something like #1473 to let users selectively pick behavior.

  11. majocha commented on Sep 26, 2026

    @majocha

    There's a toy project FSharp.Control.Async2 implementing a cold cancellable async2 builder and the asyncSeq2 IAsyncEnumerable. async2 aims to be async drop in replacement and asyncSeq2 implements functionality of both asyncSeq and taskSeq. Respectable test suites are ported. Missing part for now is MailBoxProcessor. We should definitely add a RFC, but things went fast, sorry for that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions