• Stars
    star
    203
  • Rank 191,936 (Top 4 %)
  • Language
    C#
  • License
    MIT License
  • Created over 1 year ago
  • Updated over 1 year ago

Reviews

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

Repository Details

Structured concurrency support for C#

Logo

Structured Concurrency Build status codecov NuGet version

Structured Concurrency for C#.

Task Groups

A task group provides a scope in which work is done. At the end of that scope, the task group (asynchronously) waits for all of its work to complete.

var groupTask = TaskGroup.RunGroupAsync(default, group =>
{
    group.Run(async token => await Task.Delay(TimeSpan.FromSeconds(1), token));
    group.Run(async token => await Task.Delay(TimeSpan.FromSeconds(2), token));
});
await groupTask; // Completes after 2 seconds.

A TaskGroup is started with TaskGroup.RunGroupAsync. The delegate passed to RunGroupAsync is the first work item; it can do its own work and/or add other work items to that same group. When all the work items have completed, then the group scope closes, and the task returned from RunGroupAsync completes.

Work may be added to a task group at any time by calling Run, as long as the scope has not completed. Conceptually, the task group scope ends with a kind of Task.WhenAll, but with the important difference that more work may be added after the disposal begins. As long as the work is added before all other work completes, the task group will "extend" its logical WhenAll to include the additional work.

var groupTask = TaskGroup.RunGroupAsync(default, group =>
{
    // Any group work can kick off other group work.
    group.Run(async token =>
    {
        for (int i = 0; i != 3; ++i)
        {
            await Task.Delay(TimeSpan.FromSeconds(1), token));
            group.Run(async token => await Task.Delay(TimeSpan.FromSeconds(1), token));
        }
    });
});
await groupTask; // Completes after 4 seconds.

Exceptions

If any work throws an exception (except OperationCanceledException), then that work is considered "faulted". The task group immediately enters a canceled state (see below), cancelling all of its other work.

var groupTask = TaskGroup.RunGroupAsync(default, group =>
{
    group.Run(async token =>
    {
        await Task.Delay(TimeSpan.FromSeconds(1), token);
        throw new Exception("oops");
    });

    // This task would normally take 2 seconds, but is canceled after 1 second.
    group.Run(async token => await Task.Delay(TimeSpan.FromSeconds(2), token));
});
await groupTask; // Completes after 1 second and raises Exception("oops").

At the end of the task group scope, the task group will still wait for all of its work to complete. Once all of the work has completed, then the task group task will re-raise the first exception from its faulted work.

var groupTask = TaskGroup.RunGroupAsync(default, group =>
{
    group.Run(async token =>
    {
        await Task.Delay(TimeSpan.FromSeconds(1), token);
        throw new Exception("oops");
    });

    // This task takes 2 seconds since it ignores cancellation.
    group.Run(async _ => await Task.Delay(TimeSpan.FromSeconds(2)));
});
await groupTask; // Completes after 2 seconds and raises Exception("oops").

Cancellation

Task groups always ignore any work that is cancelled (i.e., task groups catch and ignore OperationCanceledException). Task groups provide CancellationToken parameters to all of their work, and it is the work's responsibility to respond to that cancellation. The task group will cancel itself if any work item faults (with an exception other than OperationCanceledException).

Task groups also take a CancellationToken as parameter to the static RunGroupAsync methods to enable cancellation from "upstream"; e.g., if the application is shutting down. Task groups can also be cancelled manually (via TaskGroup.CancellationTokenSource) if the program logic wishes to stop the task group for any reason.

var groupTask = TaskGroup.RunGroupAsync(default, group =>
{
    // Apply a timeout for all work sent to this group.
    group.CancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(2));

    group.Run(async token => await Task.Delay(TimeSpan.FromSeconds(1), token));
    group.Run(async token => await Task.Delay(Timeout.InfiniteTimeSpan, token));
});
await groupTask; // Completes after 2 seconds.

Resources

A task group can own resources. These resources will be disposed by the task group after all its work is done.

var groupTask = TaskGroup.RunGroupAsync(default, async group =>
{
    await group.AddResourceAsync(myDisposableResource);

    group.Run(async token => await myDisposableResource.DoWorkAsync(token));
});
await groupTask; // First, waits for all tasks to complete; then, disposes myDisposableResource.

All exceptions raised by disposal of any resource are ignored.

Races

The usual pattern for task groups is to cancel on failure and ignore success. Sometimes, we want to "race" several work items to produce a result; in this case, we want the opposite: ignore failures and cancel on success.

The usual pattern is to create a race child group via TaskGroup.RaceGroupAsync. This creates a separate group along with a race result that are used for races. To race work, call Race instead of Run. The first successful Race will cancel all the others. Once all races have completed (i.e., the race child group's scope is complete), then the results of the race are returned from RaceGroupAsync.

var groupTask = TaskGroup.RaceGroupAsync<int>(default, group =>
{
    group.Race(async token => { await Task.Delay(TimeSpan.FromSeconds(1), token); return 1; });
    group.Race(async token => { await Task.Delay(TimeSpan.FromSeconds(2), token); return 2; });
    group.Race(async token => { await Task.Delay(TimeSpan.FromSeconds(3), token); return 3; });
});
var result = await groupTask; // Returns `1` after 1 second.

Successful results that lose the race are treated as resources, but are disposed immediately rather than scoped to the race child group.

More Repositories

1

AsyncEx

A helper library for async/await.
C#
3,295
star
2

Comparers

The last comparison library you'll ever need!
C#
400
star
3

Mvvm

MVVM helpers, including calculated properties and asynchronous notification tasks.
C#
132
star
4

AspNetBackgroundTasks

A component that registers "fire and forget" tasks with the ASP.NET runtime.
C#
109
star
5

Deque

Double-ended queue
C#
105
star
6

Disposables

IDisposable helper types.
C#
98
star
7

CalculatedProperties

Easy-to-use calculated properties for MVVM apps
C#
73
star
8

AsyncDiagnostics

Easy-to-use exception causality chains for async/await.
C#
61
star
9

BrowserBoss

Easily script browsers.
C#
55
star
10

Try

The Try monad (Error/Exceptional monad) for C#
C#
44
star
11

ConnectedProperties

Dynamically attach properties to (almost) any object instance.
C#
41
star
12

Guids

Helper types for creating and interpreting GUIDs.
C#
27
star
13

Presentations

Repository for presentations
C#
27
star
14

PegLeg

A PEG parser for C#, using code generators
C#
22
star
15

CrossDomainSingleton

An AppDomain-aware, thread-safe singleton that ensures only one instance exists in the entire application.
C#
22
star
16

LocalTelemetry

Local dashboards for telemetry collection.
18
star
17

Docs

Documentation of various and sundry matters
16
star
18

grounded-chatgpt

ChatGPT, but grounded in custom data
C#
16
star
19

HashAlgorithms

CRC calculation for .NET
C#
16
star
20

DependencyInjection

Helpers for Microsoft.Extensions.DependencyInjection.
C#
15
star
21

ArraySegments

A library for slicing and dicing arrays (without copying).
C#
13
star
22

Scripts

Misc single-file scripts and utilities
C#
13
star
23

ArcDb

An ACID .NET relational database
12
star
24

Mvvm.CalculatedProperties

Automatically raise PropertyChanged in MVVM applications.
C#
11
star
25

Cancellation

Types to assist with cancellation handling.
C#
11
star
26

DisplayProfiles

An application that saves and restores display monitor layouts.
C#
10
star
27

Mvvm.Core

Basic MVVM helpers.
C#
10
star
28

AsyncCTPUtil

Utility code originally distributed as part of the Async CTP
C#
10
star
29

ProjProps

A dotnet tool that displays project properties.
C#
10
star
30

Logging

Library for using scopes with Microsoft.Extensions.Logging.
C#
10
star
31

AsyncEx.Testing

Helper types for writing unit tests for asynchronous code.
C#
9
star
32

ProducerConsumerStream

A producer/consumer collection of bytes with a Stream-based API.
C#
8
star
33

OptionParsing

Flexible command-line parsing library
C#
8
star
34

BuildTools

Miscellaneous tools for building .NET Core libraries.
7
star
35

UniformResourceIdentifiers

Standard-compliant URI encoders and parsers
C#
6
star
36

iterjs

ES6 library for working with iterables and iterators
JavaScript
5
star
37

Quicly

An implementation of IETF QUIC in .NET
C#
4
star
38

StrongNamer

Simple app that strong-names NuGet packages.
C#
3
star
39

AsyncUnitTests

Helpers for async unit testing.
C#
3
star
40

blog-stephencleary-dotcom

blog.stephencleary.com
HTML
2
star
41

Hosting

.NET Generic Host for UI applications
C#
2
star
42

Collections.Async

Async-compatible producer/consumer collections.
2
star
43

comments.stephencleary.com

Comments for stephencleary.com.
JavaScript
2
star
44

stephencleary-dotcom

HTML
1
star
45

LoggerProviderHelpers

Helper types for implementing Microsoft's ILoggerProvider.
1
star
46

ARC

A simple dynamic language. Like JavaScript, but better!
C#
1
star
47

DockerLifetime

A .NET Core lifetime service for Docker containers
1
star
48

glob

GitHub Action that finds files using globs (wildcards)
JavaScript
1
star
49

Presentations-IntermediateAsync

Sample code for presentation given at GRDevDay 2013-03-02
1
star
50

Hymnals

Public domain hymnals
LilyPond
1
star