Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 37 ยท Async and Concurrency

Tasks and Parallel Code

Learn the F# task { } expression for .NET Task interop, awaiting tasks from async code, Array.Parallel and PLINQ-style parallelism, shared state pitfalls and when to use which tool.

Async workflows are F#'s own model. The rest of .NET speaks Task: HttpClient, File.ReadAllTextAsync, Entity Framework, ASP.NET Core. Since F# 6 you have a second workflow, task { }, that builds Task<'T> values directly and awaits other tasks without any conversion. This lesson covers it, then moves from concurrency (waiting for many things) to parallelism (using many cores).

The task expression

FSHARP
open System.Net.Http

let fetchLength (url: string) =
    task {
        use client = new HttpClient()
        let! body = client.GetStringAsync url
        return body.Length
    }

let t = fetchLength "https://example.com"   // Task<int>, already running

The shape is identical to async: let! awaits, return produces, try/with and use work. The differences matter:

async { } task { }
Result type Async<'T> Task<'T>
Starts when you run it (cold) immediately (hot)
Cancellation implicit token, flows automatically you pass a CancellationToken yourself
Best for F# code, retries, composition .NET libraries and ASP.NET Core

Because task { } compiles to the same state machine that C# uses, it is the right choice for hot paths and library code that C# callers will use.

C# C# stand-in: tasks start immediately (hot)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Run it and note that "A: started" appears before "task created". In F# an async block would print nothing until you ran it.

Mixing async and task

FSHARP
let asyncToTask = Async.StartAsTask (async { return 1 })      // Async -> Task
let taskToAsync = Async.AwaitTask (task { return 2 })         // Task -> Async

let mixed =
    task {
        let! x = async { return 10 }      // task { } can await an Async directly
        let! y = task { return 20 }
        return x + y
    }

Inside task { } you can let! both tasks and asyncs, which makes migration easy. Inside async { } use Async.AwaitTask on a task (or let! it directly, as F# also supports that overload).

Awaiting many tasks

FSHARP
let squares =
    task {
        let! results =
            [ 1 .. 5 ]
            |> List.map (fun n -> task { do! System.Threading.Tasks.Task.Delay 100
                                         return n * n })
            |> System.Threading.Tasks.Task.WhenAll
        return results
    }

Task.WhenAll plays the role of Async.Parallel. It returns an array of results in order.

Parallelism: using all the cores

Concurrency overlaps waiting. For CPU-bound work (hashing, number crunching, image processing) you need more threads running at once. The Array.Parallel module splits arrays across cores:

FSHARP
let isPrime n =
    n > 1 && Seq.forall (fun d -> n % d <> 0) (seq { 2 .. int (sqrt (float n)) })

let primes =
    [| 1 .. 200_000 |]
    |> Array.Parallel.filter isPrime

printfn "%d primes" primes.Length

Array.Parallel.map, filter, sum, iter, init and others mirror the normal functions. The speed-up depends on the work per item: if each step is tiny, the overhead outweighs the gain, so benchmark before trusting it. Make sure the function you pass is pure, that is, it does not change shared state.

flowchart TD
    A["I/O-bound: waiting"] --> B["async / task"]
    C["CPU-bound: computing"] --> D["Array.Parallel / Parallel.For"]
    E["Many independent jobs"] --> F["Async.Parallel / Task.WhenAll"]
    G["Shared mutable state"] --> H["Avoid, or protect with locks / agents"]

Pick the tool from the kind of bottleneck: waiting, computing, or coordinating.

C# C# stand-in: a parallel prime count

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Shared state: the bug factory

The hard part of concurrent code is not starting threads; it is shared mutable state. Two threads incrementing one counter lose updates:

FSHARP
let mutable total = 0
[| 1 .. 1000 |] |> Array.Parallel.iter (fun _ -> total <- total + 1)
// total is probably less than 1000: a race condition

Three remedies, from best to worst:

  1. Do not share. Let each thread compute its own result and combine at the end: Array.Parallel.map then Array.sum.
  2. Use an atomic operation: System.Threading.Interlocked.Increment(&total).
  3. Use a lock: lock obj (fun () -> total <- total + 1). Correct but slow and error-prone.

F# data is immutable by default, which already removes most of the problem. The agent-based approach in the next lesson offers a fourth path: put the state inside one agent that handles messages one at a time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main behavioural difference between async { } and task { }?

    A Task is already running when created; an Async is only a recipe until you run it.
  2. 2. Which workflow is generally preferred when calling HttpClient?

    task { } awaits .NET Tasks directly without conversion.
  3. 3. Which tool speeds up CPU-bound work on arrays?

    Array.Parallel splits the work over cores; async/task only overlap waiting.
  4. 4. Which is the safest cure for a race condition on a shared counter?

    Not sharing mutable state is the best fix; atomics and locks are fallbacks.

Summary

  • task { } builds hot Task<'T> values and is the natural choice for .NET interop.
  • async is cold and composes well; the two convert with Async.StartAsTask and Async.AwaitTask, and task { } can let! both.
  • Task.WhenAll is the task analogue of Async.Parallel.
  • Use Array.Parallel for CPU-bound work with pure functions.
  • Avoid shared mutable state; otherwise use Interlocked, locks or an agent.

Next: MailboxProcessor and Agents