Punchclock: A library for managing concurrent operations
Punchclock is the low-level scheduling and prioritization library used by
Fusillade to orchestrate pending
concurrent operations.
What even does that mean?
Ok, so you've got a shiny mobile phone app and you've got async/await.
Awesome! It's so easy to issue network requests, why not do it all the time?
After your users one-:star2: you for your app being slow, you discover that
you're issuing way too many requests at the same time.
Then, you try to manage issuing less requests by hand, and it becomes a
spaghetti mess as different parts of your app reach into each other to try to
figure out who's doing what. Let's figure out a better way.
Key features
- Bounded concurrency so only a fixed number of operations run at once
- Priority scheduling where higher numbers run first when a slot opens
- Key-based serialization so related work runs one-at-a-time
- Task and
IObservable<T> APIs over the same queueing engine
- Cancellation via
CancellationToken or an observable signal
- Pause/resume with reference counting
- Runtime concurrency changes with
SetMaximumConcurrent
- Shutdown that waits for queued and in-flight work to finish
- V7.0.0+ Built on
ReactiveUI.Primitives for signals, disposables, RxVoid, and sequencing
- Public API tracking for every target framework
Install
- NuGet:
dotnet add package Punchclock
Punchclock currently targets modern .NET (net10.0, net11.0) and .NET Framework (net47, net471, net472, net48, net481).
Punchclock v7.0.0 moves the queue internals and observable examples onto
ReactiveUI.Primitives. ReactiveUI.Primitives v5 keeps System.Reactive
interop explicit: the base ReactiveUI.Primitives package provides the lean
Primitives API and optional generated R3/R3Async bridges, while System.Reactive
compatibility lives in the .Reactive package variants such as
ReactiveUI.Primitives.Reactive, ReactiveUI.Primitives.Async.Reactive, and
ReactiveUI.Primitives.Extensions.Reactive.
For a v6-style System.Reactive migration, keep the Rx package while you move
code across the boundary. Punchclock returns standard BCL IObservable<T>
values, so System.Reactive LINQ can still compose queue results directly:
dotnet add package Punchclock --version 7.0.0
dotnet add package System.Reactive
# Optional when your own code needs Primitives APIs with System.Reactive Unit or IScheduler:
dotnet add package ReactiveUI.Primitives.Reactive
Then keep System.Reactive at the application edge while Punchclock schedules
the work:
using Punchclock;
using System;
using System.Net.Http;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using var queue = new OperationQueue(maximumConcurrent: 2);
using var http = new HttpClient();
using var cancelFromLegacyRx = new Subject<Unit>();
IObservable<string> rxFriendlyResult =
queue.EnqueueObservableOperation(
priority: 5,
key: "legacy:refresh",
cancel: cancelFromLegacyRx,
asyncCalculationFunc: () =>
Observable.FromAsync(() => http.GetStringAsync("https://example.com/legacy")));
using var subscription = rxFriendlyResult
.Timeout(TimeSpan.FromSeconds(10))
.Subscribe(
value => Console.WriteLine(value),
error => Console.Error.WriteLine(error));
cancelFromLegacyRx.OnNext(Unit.Default);
R3 and R3Async bridge adapters are still generated from the base
ReactiveUI.Primitives package in the ReactiveUI.Primitives.R3Bridge
namespace when the consuming project references R3 or R3Async. There is no
generated System.Reactive bridge namespace in ReactiveUI.Primitives v5; use the
.Reactive packages when your own Primitives-facing code must expose
System.Reactive Unit or IScheduler.
Most application code only needs this:
using Punchclock;
Observable examples also use the ReactiveUI.Primitives signal helpers:
using ReactiveUI.Primitives;
using ReactiveUI.Primitives.Concurrency;
using ReactiveUI.Primitives.Signals;
Quick start
using Punchclock;
using System.Net.Http;
using var queue = new OperationQueue(maximumConcurrent: 2);
using var http = new HttpClient();
// Fire a bunch of downloads. Only two will run at a time.
var t1 = queue.Enqueue(1, () => http.GetStringAsync("https://example.com/a"));
var t2 = queue.Enqueue(1, () => http.GetStringAsync("https://example.com/b"));
var t3 = queue.Enqueue(10, () => http.GetStringAsync("https://example.com/urgent"));
await Task.WhenAll(t1, t2, t3);
In 60 seconds
Create one queue near the part of your app that owns the work, then send work
through it instead of letting every caller start its own request immediately.
using Punchclock;
using var queue = new OperationQueue(maximumConcurrent: 4);
Task<string> LoadProfile(int userId) =>
queue.Enqueue(
priority: 5,
key: $"user:{userId}",
asyncOperation: () => api.GetProfileAsync(userId));
Task<string> LoadTimeline(int userId) =>
queue.Enqueue(
priority: 1,
key: $"user:{userId}",
asyncOperation: () => api.GetTimelineAsync(userId));
var profile = LoadProfile(42);
var timeline = LoadTimeline(42);
await Task.WhenAll(profile, timeline);
Those two operations share the same key, so they will not run at the same time.
Other keys can still use the remaining concurrency slots.
Priorities
Higher numbers win. A priority 10 operation is chosen ahead of priority 1
when a slot opens.
await queue.Enqueue(10, () => http.GetStringAsync("https://example.com/urgent"));
Priorities do not cancel work that is already running. They decide which pending
operation gets the next available slot.
Equal-priority operations are FIFO by default. If you want to avoid one caller
always winning equal-priority tie-breaks across different keys, enable
randomization:
using var queue = new OperationQueue(
maximumConcurrent: 4,
randomizeEqualPriority: true,
seed: null);
Use a seed when you want deterministic randomized ordering in tests:
using var queue = new OperationQueue(4, randomizeEqualPriority: true, seed: 1234);
Keys: serialize related work
- Use a key to ensure only one operation for that key runs at a time.
- Useful to avoid thundering herds against the same resource.
- Different keys can run together up to the queue's concurrency limit.
null, string.Empty, and the internal default key are treated as non-keyed work.
// These will run one-after-another because they share the same key.
var k1 = queue.Enqueue(
priority: 1,
key: "user:42",
asyncOperation: () => LoadUserAsync(42));
var k2 = queue.Enqueue(
priority: 1,
key: "user:42",
asyncOperation: () => LoadUserPostsAsync(42));
await Task.WhenAll(k1, k2);
Use keys for the resource you are protecting, not for the operation type:
await Task.WhenAll(
queue.Enqueue(
priority: 1,
key: "file:avatar.png",
asyncOperation: () => ResizeAsync("avatar.png")),
queue.Enqueue(
priority: 1,
key: "file:avatar.png",
asyncOperation: () => UploadAsync("avatar.png")),
queue.Enqueue(
priority: 1,
key: "file:banner.png",
asyncOperation: () => UploadAsync("banner.png")));
The two avatar.png operations serialize. The banner.png operation can run
beside them if a slot is available.
Cancellation
Via CancellationToken:
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
await queue.Enqueue(
priority: 1,
key: "img:1",
asyncOperation: () => DownloadImageAsync("/1"),
token: cts.Token);
Via an observable cancellation signal:
using ReactiveUI.Primitives;
using ReactiveUI.Primitives.Signals;
var cancel = new Signal<RxVoid>();
var obs = queue.EnqueueObservableOperation(
priority: 1,
key: "slow",
cancel: cancel,
asyncCalculationFunc: () => Signal.FromTask(ExpensiveAsync()));
using var subscription = obs.Subscribe(
value => Console.WriteLine(value),
error => Console.Error.WriteLine(error));
cancel.OnNext(RxVoid.Default); // Cancels if pending or while observed in-flight.
An already-canceled CancellationToken returns a canceled task without queueing
anything. A non-cancelable token uses a fast path with no cancellation
registration.
When an observable cancellation signal fires before the operation is evaluated,
the operation factory is not invoked.
Pause and resume
using var gate = queue.PauseQueue();
// Enqueue work while paused; nothing new executes yet.
// ...
gate.Dispose(); // Resumes and drains respecting priority/keys.
Pause is reference counted. If two callers pause the queue, the queue resumes
only after both returned handles have been disposed.
In-flight operations are not canceled by pausing. Pause only stops dispatching
new work.
Adjust concurrency at runtime
queue.SetMaximumConcurrent(8); // increases throughput
You can increase or decrease the concurrency limit while the queue is alive.
The value must be positive; constructors and SetMaximumConcurrent throw
ArgumentOutOfRangeException for zero or negative values.
Lowering the value does not cancel already-running operations. It limits future
dispatch until the active count drops below the new limit.
Shutting down
using ReactiveUI.Primitives.Concurrency;
await queue.ShutdownQueue().ToTask();
ShutdownQueue starts shutdown and returns an IObservable<RxVoid> that
signals when queued and in-flight operations have finished. After shutdown has
started, new enqueue attempts throw InvalidOperationException.
Calling ShutdownQueue more than once is safe. Repeated calls return the same
shutdown observable.
ReactiveUI.Primitives base
Punchclock now uses ReactiveUI.Primitives as its reactive foundation. The
public API still feels small:
- Task callers use
queue.Enqueue(...).
- Observable callers use
queue.EnqueueObservableOperation(...).
- Void observable signals use
RxVoid instead of Unit.
- Cancellation and examples use
Signal<T>.
- Advanced scheduling can be controlled with
ISequencer.
This keeps the queue independent from any UI framework while still giving
ReactiveUI-style applications a natural observable API.
using Punchclock;
using ReactiveUI.Primitives;
using ReactiveUI.Primitives.Concurrency;
using ReactiveUI.Primitives.Signals;
using var queue = new OperationQueue(maximumConcurrent: 1);
IObservable<string> pending = queue.EnqueueObservableOperation(
priority: 3,
key: "refresh",
asyncCalculationFunc: () => Signal.FromTask(RefreshAsync()));
string result = await pending.ToTask();
Task API
Use the Task API when your application is already written with async/await.
It is the most direct API for app code.
Task SaveAsync(Document document, CancellationToken token) =>
queue.Enqueue(
priority: 5,
key: $"document:{document.Id}",
asyncOperation: () => repository.SaveAsync(document, token),
token: token);
Non-generic operations return Task:
await queue.Enqueue(
priority: 1,
key: "cache:trim",
asyncOperation: () => cache.TrimAsync());
Generic operations return Task<T>:
User user = await queue.Enqueue(
priority: 3,
key: "user:42",
asyncOperation: () => api.GetUserAsync(42));
Leave the key out when the operation does not need serialization:
var response = await queue.Enqueue(
priority: 1,
asyncOperation: () => http.GetStringAsync("https://example.com/status"));
Observable API
Use the observable API when you want to compose the queued operation with other
observable streams.
IObservable<byte[]> image = queue.EnqueueObservableOperation(
priority: 2,
key: "image:42",
asyncCalculationFunc: () => Signal.FromTask(DownloadImageAsync(42)));
using var subscription = image.Subscribe(bytes =>
{
Console.WriteLine($"Downloaded {bytes.Length} bytes");
});
With an observable cancellation signal:
var cancel = new Signal<RxVoid>();
IObservable<SearchResult> search = queue.EnqueueObservableOperation(
priority: 10,
key: "search",
cancel: cancel,
asyncCalculationFunc: () => Signal.FromTask(SearchAsync("punchclock")));
using var subscription = search.Subscribe(result => Render(result));
cancel.OnNext(RxVoid.Default);
Operation factory exceptions and operation observable errors flow to that
operation's result. The queue still releases capacity and continues processing
later work.
Custom sequencing
Most apps can use the default Sequencer.Immediate. Tests and hosts with their
own execution model can pass an ISequencer.
using ReactiveUI.Primitives.Concurrency;
ISequencer sequencer = Sequencer.Immediate;
using var queue = new OperationQueue(maximumConcurrent: 2, scheduler: sequencer);
The sequencer controls when scheduled operations are started after they have
been selected by the queue.
API overview
OperationQueue
Constructors:
new OperationQueue();
new OperationQueue(int maximumConcurrent);
new OperationQueue(int maximumConcurrent, ISequencer scheduler);
new OperationQueue(int maximumConcurrent, bool randomizeEqualPriority, int? seed);
new OperationQueue(
int maximumConcurrent,
bool randomizeEqualPriority,
int? seed,
ISequencer? scheduler);
The default constructor uses maximumConcurrent: 4. Any constructor that takes
maximumConcurrent requires a positive value.
Observable enqueue methods: