• Stars
    star
    120
  • Rank 295,983 (Top 6 %)
  • Language
    F#
  • License
    MIT License
  • Created over 2 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

F# Cold Tasks and Cancellable Tasks

IcedTasks

What is IcedTasks?

This library contains additional computation expressions for the task CE utilizing the Resumable Code introduced in F# 6.0.

  • ValueTask<'T> - This utilizes .NET's ValueTask (which is essentially a Discriminated Union of 'Value | Task<'Value>) for possibly better performance in synchronous scenarios. Similar to F#'s Task Expression

    • valueTask
    • valueTaskUnit
    • poolingValueTask
  • ColdTask<'T> - Alias for unit -> Task<'T>. Allows for lazy evaluation (also known as Cold) of the tasks, similar to F#'s Async being cold.

    • coldTask
  • CancellableTask<'T> - Alias for CancellationToken -> Task<'T>. Allows for lazy evaluation (also known as Cold) of the tasks, similar to F#'s Async being cold. Additionally, allows for flowing a CancellationToken through the computation, similar to F#'s Async cancellation support.

    • cancellableTask
    • cancellableBackgroundTask
  • CancellableValueTask<'T> - Alias for CancellationToken -> ValueTask<'T>. Allows for lazy evaluation (also known as Cold) of the tasks, similar to F#'s Async being cold. Additionally, allows for flowing a CancellationToken through the computation, similar to F#'s Async cancellation support.

    • cancellableValueTask
    • cancellablePoolingValueTask
  • ParallelAsync<'T> - Utilizes the applicative syntax to allow parallel execution of Async<'T> expressions. See this discussion as to why this is a separate computation expression.

    • parallelAsync
  • AsyncEx<'T> - Variation of F# async semantics described further below with examples.

    • asyncEx
    • This can also be accessed under IcedTasks.Polyfill.Async which will shadow the F# Async CE.
      • async
  • Task<'T> - Polyfill for fixes to F# Task CE. Can be accessed under IcedTasks.Polyfill.Task which will shadow the F# Task CE.

    • task
    • backgroundTask
  • Task - a CE for a Task that has no return value.

    • taskUnit
    • backgroundTaskUnit

Differences at a glance

Computation Expression1 Library2 TFM3 Hot/Cold4 Multiple Awaits 5 Multi-start6 Tailcalls7 CancellationToken propagation8 Cancellation checks9 Parallel when using and!10 use IAsyncDisposable 11
F# Async FSharp.Core netstandard2.0 Cold Multiple multiple tailcalls implicit implicit No No
F# AsyncEx IcedTasks netstandard2.0 Cold Multiple multiple tailcalls implicit implicit No Yes
F# ParallelAsync IcedTasks netstandard2.0 Cold Multiple multiple tailcalls implicit implicit Yes No
F# Task/C# Task FSharp.Core netstandard2.0 Hot Multiple once-start no tailcalls explicit explicit No Yes
F# ValueTask IcedTasks netstandard2.1 Hot Once once-start no tailcalls explicit explicit Yes Yes
F# ColdTask IcedTasks netstandard2.0 Cold Multiple multiple no tailcalls explicit explicit Yes Yes
F# CancellableTask IcedTasks netstandard2.0 Cold Multiple multiple no tailcalls implicit implicit Yes Yes
F# CancellableValueTask IcedTasks netstandard2.1 Cold Once multiple no tailcalls implicit implicit Yes Yes
  • 1 - Computation Expression
  • 2 - Which Nuget package do they come from
  • 3 - Which Target Framework Moniker these are available in
  • 4 - Hot refers to the asynchronous code block already been started and will eventually produce a value. Cold refers to the asynchronous code block that is not started and must be started explicitly by caller code. See F# Async Tutorial and Asynchronous C# and F# (II.): How do they differ? for more info.
  • 5 - ValueTask Awaiting patterns
  • 6 - Multi-start refers to being able to start the asynchronous code block again. See FAQ on Task Start for more info.
  • 7 - Allows use of let rec with the computation expression. See Tail call Recursion for more info.
  • 8 - CancellationToken is propagated to all types the support implicit CancellatationToken passing. Calling cancellableTask { ... } nested inside async { ... } (or any of those combinations) will use the CancellationToken from when the code was started.
  • 9 - Cancellation will be checked before binds and runs.
  • 10 - Allows parallel execution of the asynchronous code using the Applicative Syntax in computation expressions.
  • 11 - Allows use of IAsyncDisposable with the computation expression. See IAsyncDisposable for more info.

Why should I use this?

AsyncEx

AsyncEx is similar to Async except in the following ways:

  1. Allows use for IAsyncDisposable

    open IcedTasks
    let fakeDisposable () = { new IAsyncDisposable with member __.DisposeAsync() = ValueTask.CompletedTask }
    
    let myAsyncEx = asyncEx {
        use _ = fakeDisposable ()
        return 42
    }
  2. Allows let!/do! against Tasks/ValueTasks/any Awaitable

    open IcedTasks
    let myAsyncEx = asyncEx {
        let! _ = task { return 42 } // Task<T>
        let! _ = valueTask { return 42 } // ValueTask<T>
        let! _ = Task.Yield() // YieldAwaitable
        return 42
    }
  3. When Tasks throw exceptions they will use the behavior described in Async.Await overload (esp. AwaitTask without throwing AggregateException

    let data = "lol"
    
    let inner = asyncEx {
        do!
            task {
                do! Task.Yield()
                raise (ArgumentException "foo")
                return data
            }
            :> Task
    }
    
    let outer = asyncEx {
        try
            do! inner
            return ()
        with
        | :? ArgumentException ->
            // Should be this exception and not AggregationException
            return ()
        | ex ->
            return raise (Exception("Should not throw this type of exception", ex))
    }
  4. Use IAsyncEnumerable with for keyword. This example uses TaskSeq but you can use any IAsyncEnumerable<T>.

    open IcedTasks
    open FSharp.Control
    let myAsyncEx = asyncEx {
        let items = taskSeq {  // IAsyncEnumerable<T>
            yield 42
            do! Task.Delay(100)
            yield 1701
        }
        let mutable sum = 0
        for i in items do
            sum <- sum + i
        return sum
    }

For ValueTasks

open IcedTasks

let myValueTask = task {
    let! theAnswer = valueTask { return 42 }
    return theAnswer
}

For Cold & CancellableTasks

  • You want control over when your tasks are started
  • You want to be able to re-run these executable tasks
  • You don't want to pollute your methods/functions with extra CancellationToken parameters
  • You want the computation to handle checking cancellation before every bind.

ColdTask

Short example:

open IcedTasks

let coldTask_dont_start_immediately = task {
    let mutable someValue = null
    let fooColdTask = coldTask { someValue <- 42 }
    do! Async.Sleep(100)
    // ColdTasks will not execute until they are called, similar to how Async works
    Expect.equal someValue null ""
    // Calling fooColdTask will start to execute it
    do! fooColdTask ()
    Expect.equal someValue 42 ""
}

CancellableTask & CancellableValueTask

The examples show cancellableTask but cancellableValueTask can be swapped in.

Accessing the context's CancellationToken:

  1. Binding against CancellationToken -> Task<_>

    let writeJunkToFile = 
        let path = Path.GetTempFileName()
    
        cancellableTask {
            let junk = Array.zeroCreate bufferSize
            use file = File.Create(path)
    
            for i = 1 to manyIterations do
                // You can do! directly against a function with the signature of `CancellationToken -> Task<_>` to access the context's `CancellationToken`. This is slightly more performant.
                do! fun ct -> file.WriteAsync(junk, 0, junk.Length, ct)
        }
  2. Binding against CancellableTask.getCancellationToken

    let writeJunkToFile = 
        let path = Path.GetTempFileName()
    
        cancellableTask {
            let junk = Array.zeroCreate bufferSize
            use file = File.Create(path)
            // You can bind against `CancellableTask.getCancellationToken` to get the current context's `CancellationToken`.
            let! ct = CancellableTask.getCancellationToken ()
            for i = 1 to manyIterations do
                do! file.WriteAsync(junk, 0, junk.Length, ct)
        }

Short example:

let executeWriting = task {
    // CancellableTask is an alias for `CancellationToken -> Task<_>` so we'll need to pass in a `CancellationToken`.
    // For this example we'll use a `CancellationTokenSource` but if you were using something like ASP.NET, passing in `httpContext.RequestAborted` would be appropriate.
    use cts = new CancellationTokenSource()
    // call writeJunkToFile from our previous example
    do! writeJunkToFile cts.Token
}

ParallelAsync

  • When you want to execute multiple asyncs in parallel and wait for all of them to complete.

Short example:

open IcedTasks

let exampleHttpCall url = async {
    // Pretend we're executing an HttpClient call
    return 42
}

let getDataFromAFewSites = parallelAsync {
    let! result1 = exampleHttpCall "howManyPlantsDoIOwn"
    and! result2 = exampleHttpCall "whatsTheTemperature"
    and! result3 = exampleHttpCall "whereIsMyPhone"

    // Do something meaningful with results
    return ()
}

Builds

GitHub Actions
GitHub Actions
Build History

NuGet

Package Stable Prerelease
IcedTasks NuGet Badge NuGet Badge

Developing

Make sure the following requirements are installed on your system:

or


Environment Variables

  • CONFIGURATION will set the configuration of the dotnet commands. If not set, it will default to Release.
    • CONFIGURATION=Debug ./build.sh will result in -c additions to commands such as in dotnet build -c Debug
  • GITHUB_TOKEN will be used to upload release notes and Nuget packages to GitHub.
    • Be sure to set this before releasing
  • DISABLE_COVERAGE Will disable running code coverage metrics. AltCover can have severe performance degradation so it's worth disabling when looking to do a quicker feedback loop.
    • DISABLE_COVERAGE=1 ./build.sh

Building

> build.cmd <optional buildtarget> // on windows
$ ./build.sh  <optional buildtarget>// on unix

The bin of your library should look similar to:

$ tree src/MyCoolNewLib/bin/
src/MyCoolNewLib/bin/
└── Debug
    └── net50
        ├── MyCoolNewLib.deps.json
        ├── MyCoolNewLib.dll
        ├── MyCoolNewLib.pdb
        └── MyCoolNewLib.xml

Build Targets

  • Clean - Cleans artifact and temp directories.
  • DotnetRestore - Runs dotnet restore on the solution file.
  • DotnetBuild - Runs dotnet build on the solution file.
  • DotnetTest - Runs dotnet test on the solution file.
  • GenerateCoverageReport - Code coverage is run during DotnetTest and this generates a report via ReportGenerator.
  • WatchTests - Runs dotnet watch with the test projects. Useful for rapid feedback loops.
  • GenerateAssemblyInfo - Generates AssemblyInfo for libraries.
  • DotnetPack - Runs dotnet pack. This includes running Source Link.
  • SourceLinkTest - Runs a Source Link test tool to verify Source Links were properly generated.
  • PublishToNuGet - Publishes the NuGet packages generated in DotnetPack to NuGet via paket push.
  • GitRelease - Creates a commit message with the Release Notes and a git tag via the version in the Release Notes.
  • GitHubRelease - Publishes a GitHub Release with the Release Notes and any NuGet packages.
  • FormatCode - Runs Fantomas on the solution file.
  • BuildDocs - Generates Documentation from docsSrc and the XML Documentation Comments from your libraries in src.
  • WatchDocs - Generates documentation and starts a webserver locally. It will rebuild and hot reload if it detects any changes made to docsSrc files, libraries in src, or the docsTool itself.
  • ReleaseDocs - Will stage, commit, and push docs generated in the BuildDocs target.
  • Release - Task that runs all release type tasks such as PublishToNuGet, GitRelease, ReleaseDocs, and GitHubRelease. Make sure to read Releasing to setup your environment correctly for releases.

Releasing

git add .
git commit -m "Scaffold"
git remote add origin https://github.com/user/MyCoolNewLib.git
git push -u origin master
  • Create your NuGeT API key

    paket config add-token "https://www.nuget.org" 4003d786-cc37-4004-bfdf-c4f3e8ef9b3a
    • or set the environment variable NUGET_TOKEN to your key
  • Create a GitHub OAuth Token

    • You can then set the environment variable GITHUB_TOKEN to upload release notes and artifacts to github
    • Otherwise it will fallback to username/password
  • Then update the CHANGELOG.md with an "Unreleased" section containing release notes for this version, in KeepAChangelog format.

NOTE: Its highly recommend to add a link to the Pull Request next to the release note that it affects. The reason for this is when the RELEASE target is run, it will add these new notes into the body of git commit. GitHub will notice the links and will update the Pull Request with what commit referenced it saying "added a commit that referenced this pull request". Since the build script automates the commit message, it will say "Bump Version to x.y.z". The benefit of this is when users goto a Pull Request, it will be clear when and which version those code changes released. Also when reading the CHANGELOG, if someone is curious about how or why those changes were made, they can easily discover the work and discussions.

Here's an example of adding an "Unreleased" section to a CHANGELOG.md with a 0.1.0 section already released.

## [Unreleased]

### Added
- Does cool stuff!

### Fixed
- Fixes that silly oversight

## [0.1.0] - 2017-03-17
First release

### Added
- This release already has lots of features

[Unreleased]: https://github.com/user/MyCoolNewLib.git/compare/v0.1.0...HEAD
[0.1.0]: https://github.com/user/MyCoolNewLib.git/releases/tag/v0.1.0
  • You can then use the Release target, specifying the version number either in the RELEASE_VERSION environment variable, or else as a parameter after the target name. This will:
    • update CHANGELOG.md, moving changes from the Unreleased section into a new 0.2.0 section
      • if there were any prerelease versions of 0.2.0 in the changelog, it will also collect their changes into the final 0.2.0 entry
    • make a commit bumping the version: Bump version to 0.2.0 and adds the new changelog section to the commit's body
    • publish the package to NuGet
    • push a git tag
    • create a GitHub release for that git tag

macOS/Linux Parameter:

./build.sh Release 0.2.0

macOS/Linux Environment Variable:

RELEASE_VERSION=0.2.0 ./build.sh Release

More Repositories

1

MiniScaffold

F# Template for creating and publishing libraries targeting .NET 6.0 `net6.0` or console apps .NET 6.0 `net6.0`.
F#
269
star
2

Marten.FSharp

A set of FSharp wrappers around Marten
F#
73
star
3

RxSandbox

C#
72
star
4

FSharp.Control.WebSockets

FSharp.Control.WebSockets wraps dotnet WebSockets in FSharp friendly functions and has a ThreadSafe version.
F#
68
star
5

FsLibLog

FsLibLog is a single file you can copy paste or add through Paket Github dependencies to provide your F# library with a logging abstraction. This is a port of the C# LibLog.
F#
55
star
6

dotnet-mono

dotnet utility to run .net full apps using mono on OSX/Linux
F#
51
star
7

dotnet-drama

F#
30
star
8

dotnet-web-benchmarks

Benchmarks of popular .net web frameworks
Lua
22
star
9

FsOpenTelemetry

FsOpenTelemetry is a single file you can copy paste or add through Paket Github dependencies to provide your F# library with safe helpers for Activity and ActivitySource.
F#
22
star
10

Fable.Template.Library

F# Template for create and publishing Fable Libraries
F#
20
star
11

FableInLegacyApps

JavaScript
20
star
12

paket-lock-diff

This is a tool to analyze two paket.lock files showing additions, removals, upgrades and downgrades.
F#
17
star
13

TypeSafeInternals

Uses Myriad to generate type safe reflection calls to internal functions/properties/methods.
F#
14
star
14

FSharp.Control.Redis.Streams

Interop library between Redis Streams and popular dotnet streaming libraries
F#
13
star
15

Hopac.Websockets

Threadsafe Hopac wrapper around Websockets
F#
7
star
16

Giraffe.Hopac

F#
6
star
17

uhura

Lua
6
star
18

docker-canopy

Using F# Canopy in Docker image
F#
6
star
19

FSharp.TPLDataflow

F#
5
star
20

MEL.Flex

FSharp Logging EXtensions for Microsoft.Extensions.Logging
F#
5
star
21

FableWithIdentityServer

F#
4
star
22

MetroPass

C#
4
star
23

StreamOfDreams

F#
3
star
24

DisposableExamples

F#
3
star
25

fantasy

JavaScript
3
star
26

LogaryTools

F#
3
star
27

Fsharp-DI-Bridge

F#
3
star
28

ReactiveOperators

Extensions to the beloved Reactive Extensions.
PowerShell
3
star
29

FSharp.Analyzers

F#
2
star
30

BenchmarkDotNet.Template

BenchmarkDotNet.Template
F#
2
star
31

miniscaffold-slides

http://www.jimmybyrd.me/miniscaffold-slides/index.html#/
F#
2
star
32

litterbox

Similar functionality as dotnet-dump but available via F# Interactive instead. formerly fsi-dotnet-dump-analyzer
F#
2
star
33

mkbundle-example

F#
1
star
34

Chessie.Hopac

Combines the best of Hopac and Chessie to create a JobTrial
F#
1
star
35

ThePaperWallDownloaded

Downloads the latest ThePaperWall.com themes
C#
1
star
36

2014-M3Conf-ReactiveUI

C#
1
star
37

keto-recipes

Keto recipes I make from time to time
1
star
38

ReactiveExtensionsDemo

C#
1
star
39

Hopac-The-Other-Async

F#
1
star