FSharp.Control.TaskSeq
FSharp.Control.TaskSeq provides a taskSeq computation expression for IAsyncEnumerable<'T>,
along with a comprehensive TaskSeq module.
An task sequence is an asynchronous sequence in which individual elements are awaited:
the next element is not necessarily available immediately.
Under the hood each taskSeq { ... } is an IAsyncEnumerable<'T> — the .NET standard
interface used by C# await foreach, Entity Framework Core, gRPC streaming, and many other
libraries in the ecosystem.
Quick Start
Add the NuGet package FSharp.Control.TaskSeq
to your project and open the namespace:
// #r "nuget: FSharp.Control.TaskSeq"
open FSharp.Control
A TaskSeq<'T> can be created with the taskSeq { ... } computation expression:
let oneThenTwo = taskSeq {
yield 1
do! Task.Delay 1000 // non-blocking sleep
yield 2
}
When iterated, the sequence above yields 1 immediately and 2 after one second. Consumers
must await each step.
Use await foreach in C#, or any TaskSeq consumer in F#:
// Iterate with a for loop inside a task { ... }
task {
for item in oneThenTwo do
printfn "Got %d" item
} |> Task.Run |> ignore
// Or use TaskSeq.iter
do! oneThenTwo |> TaskSeq.iter (printfn "Got %d")
Topics
- Generating sequences —
taskSeq { },init,unfold,ofArray, … - Transforming sequences —
map,filter,choose,collect, … - Consuming sequences —
iter,fold,find,toArray,sum, … - Combining sequences —
append,zip,take,skip,chunkBySize, … - Advanced operations —
groupBy,mapFold,distinct,partition, …
Comparison with FSharp.Control.AsyncSeq
FSharp.Control.AsyncSeq is the
predecessor library, oriented towards Async<'T>.
Both libraries implement IAsyncEnumerable<'T> so they are interoperable.
The main differences are:
|
|
|
|---|---|---|
Async model |
|
|
Performance |
Higher (resumable state machines) |
Good |
.NET interop |
Native |
Native |
Cancellation |
|
Built in to |
Related links
namespace Microsoft.FSharp
--------------------
namespace FSharp
FSharp.Control.TaskSeq