Spargine is a collection of open-source assemblies and NuGet packages designed for .NET 10, which I have been developing and maintaining since the release of .NET Framework 2. These assemblies are not only a core part of my projects but are also actively deployed in production environments across several companies I collaborate with.
Get Spargine
You can access the source code and NuGet packages here:
- GitHub: Spargine 10
- NuGet: dotNetDaveNuGet
Background work can improve responsiveness, but an application still needs a way to track that work and observe failures before it exits. That becomes especially important when it is time to shut down.
While working on the Spargine Dev Tool, I wanted to move noncritical operations out of the main execution path. I also needed to keep track of those operations so the tool could give them time to finish before shutting down. That led me to create TaskTracker.
Available in the DotNetTips.Spargine.Core NuGet package, the task tracking types live in the DotNetTips.Spargine.Core.Threading namespace. They provide a thread-safe way to register tasks, check pending work, forward exceptions to a logging callback, and wait for tracked tasks to finish. The ITaskTracker interface also makes the tracker easy to use with dependency injection.
Task Tracking Types
TaskTracker
TaskTracker implements ITaskTracker, which defines the tracking contract and inherits IDisposable. It uses a concurrent dictionary to track tasks by Ulid registration keys and automatically removes each task when it completes. Registering an existing task adds tracking; it does not start that task.
Pending Work
bool HasPendingTasks { get; }
Returns true while the tracker contains registered tasks. I use this property in the Spargine Dev Tool when deciding whether background work is still outstanding. Treat it as a point-in-time view; use WaitForCompletionAsync() when you need to wait.
int GetPendingCount()
Returns the current number of tasks in the tracker. This method also provides a point-in-time snapshot, so the value can change immediately as tasks finish.
Registration and Completion
Ulid Register(Task task, Action<Exception>? onException = null)
Registers a task and returns its unique registration key. If the task faults, the optional onException callback receives the task’s AggregateException. TaskTracker observes the fault even when no callback is supplied. Canceled tasks do not invoke this callback.
void Unregister(Task task)
Removes the task from tracking. Calling it for a task that is not tracked is safe. Unregistering does not cancel or stop the task.
bool Unregister(Ulid key)
Removes a registration by its key. Returns true if the registration was removed; otherwise, returns false. The underlying task continues running.
Task<bool> WaitForCompletionAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Waits for a snapshot of the tasks registered when the method is called. Tasks registered afterward are not included in that wait. The default timeout is 30 seconds; use Timeout.InfiniteTimeSpan for an unlimited wait.
A true result means the snapshot reached completion, including tasks that faulted or were canceled. TaskTracker does not rethrow their exceptions from this method. In the current implementation, a timeout or cancellation of the wait returns false. Neither condition cancels the tracked tasks.
void Dispose()
Marks the tracker as disposed and clears its registrations. It does not wait for, cancel, or stop the underlying tasks. Complete your shutdown wait before disposing the tracker.
TaskTrackerFacade
TaskTrackerFacade provides static access to a lazily created, shared TaskTracker. Use it when an application needs a common tracker without passing an instance to every caller. Its Instance property exposes that tracker as ITaskTracker.
bool HasPendingTasks { get; }
Returns whether the shared tracker contains pending registrations.
ITaskTracker Instance { get; }
Returns the default shared tracker.
The façade forwards the following methods to the shared tracker, with the same behavior described above:
int GetPendingCount()
Gets the current count of tracked, not-yet-completed tasks. This is a point-in-time snapshot.
Ulid Register(Task task, Action<Exception>? onException = null)
void Unregister(Task task)
bool Unregister(Ulid key)
Task<bool> WaitForCompletionAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)
The shared instance belongs to the application’s overall lifetime. Avoid disposing it at the end of an individual operation, because later callers will receive the same disposed instance.
TaskTrackerExtensions
TaskTrackerExtensions simplifies registering existing tasks and starting tracked work for individual items or batches. Every extension accepts an optional tracker and exception callback. When tracker is null, the extension uses TaskTrackerFacade.Instance.
Ulid RegisterWithTracker(this Task task, ITaskTracker? tracker = null, Action<Exception>? onException = null)
Registers an already-started (hot) task so it can be monitored or waited for later without being awaited at the call site. TaskTracker observes faults and forwards the task’s AggregateException to onException when supplied. If tracker is null, the shared TaskTrackerFacade.Instance is used.
This method does not start cold tasks created with new Task(...). Passing a null task throws ArgumentNullException. With TaskTracker, registering a task that is still tracked returns its existing Ulid key.
Ulid RegisterItemWithTracker<T>(this T item, Action<T> action, ITaskTracker? tracker = null, Action<Exception>? onException = null)
Uses Task.Run() to execute a synchronous action for one item, registers the resulting task, and returns its key.
Ulid RegisterItemWithTrackerAsync<T>(this T item, Func<T, Task> action, ITaskTracker? tracker = null, Action<Exception>? onException = null)
Uses Task.Run() to execute an asynchronous function for one item and tracks its returned task through completion. The method immediately returns a registration key, rather than a Task to await.
ReadOnlyCollection<Ulid> RegisterManyWithTracker<T>(this ReadOnlySpan<T> items, Action<T> action, ITaskTracker? tracker = null, Action<Exception>? onException = null)
Starts and registers one Task.Run() operation per item using a synchronous action. Returns a read-only collection of registration keys in the same order as the input items.
ReadOnlyCollection<Ulid> RegisterManyWithTrackerAsync<T>(this ReadOnlySpan<T> items, Func<T, Task> action, ITaskTracker? tracker = null, Action<Exception>? onException = null)
Starts and registers one Task.Run() operation per item using an asynchronous function. It immediately returns the registration keys; use the tracker to wait for the work.
Exporting a Batch of Invoices
The following .NET console example uses RegisterManyWithTracker to export customer invoices. It follows the same pattern I use in the Spargine Dev Tool: start background work, log failures, and wait before the process exits.
Each invoice is written to a separate file. The invoice numbers must be unique within the batch to prevent concurrent writes to the same path. Existing files with the same names are overwritten.
using DotNetTips.Spargine.Core.Threading;
internal static class Program
{
private static async Task Main()
{
Invoice[] invoices =
[
new(1001, "Contoso Ltd.", 1499.00m),
new(1002, "Northwind Traders", 725.50m),
new(1003, "Adventure Works", 2180.75m)
];
var outputDirectory = Path.Combine(AppContext.BaseDirectory, "Invoices");
Directory.CreateDirectory(outputDirectory);
using var tracker = new TaskTracker();
ReadOnlySpan<Invoice> invoiceBatch = invoices;
// Create and register one task per invoice.
var registrationKeys = invoiceBatch.RegisterManyWithTracker(action: invoice => WriteInvoice(invoice, outputDirectory), tracker: tracker, onException: exception => Console.Error.WriteLine($"Invoice export failed: {exception}"));
Console.WriteLine($"Registered {registrationKeys.Count} invoice export tasks.");
// Keep the console app running until all tasks finish.
await tracker.WaitForCompletionAsync(timeout: Timeout.InfiniteTimeSpan);
// Finished tasks can include failed exports.
Console.WriteLine("All invoice tasks have finished.");
Console.WriteLine($"Output directory: {outputDirectory}");
}
private static void WriteInvoice(Invoice invoice, string outputDirectory)
{
var content = FormattableString.Invariant($"""Invoice: {invoice.Number} Customer: {invoice.Customer} Amount due (USD): {invoice.Amount:F2}""");
// Unique numbers avoid concurrent writes to the same file.
var filePath = Path.Combine(outputDirectory, $"Invoice-{invoice.Number}.txt");
File.WriteAllText(filePath, content, Encoding.UTF8);
}
private sealed record Invoice(int Number, string Customer, decimal Amount);
}
RegisterManyWithTracker returns after scheduling and registering the work; it does not wait for the invoice exports. The explicit wait keeps the console application alive until the tracked task bodies finish. Completion includes failed exports, which are reported through onException.
This example deliberately demonstrates the synchronous Action<T> overload. For asynchronous file or network operations, use RegisterManyWithTrackerAsync with a Func<T, Task>. An async lambda passed to the Action<T> overload becomes async void, which prevents the tracker from reliably tracking the entire operation.
The batch extensions do not limit concurrency. For large inputs, process bounded batches or limit concurrent work inside the operation to avoid overwhelming the thread pool or a downstream resource.
Dependency Injection and Shutdown
Register TaskTracker through ITaskTracker to share a tracker across services in an application:
using Microsoft.Extensions.DependencyInjection;
using DotNetTips.Spargine.Core.Threading;
services.AddSingleton<ITaskTracker, TaskTracker>();
Here, services is your application’s IServiceCollection. Register TaskTrackerFacade.Instance instead if you want to share the facade’s tracker. A dedicated tracker, as in the invoice example, lets you wait for one batch independently.
At shutdown, stop registering new work before calling WaitForCompletionAsync() so its snapshot covers the outstanding work. Choose an appropriate timeout and handle a false result before disposing the tracker.
Keep exception callbacks short and thread-safe. TaskTracker suppresses exceptions thrown by callbacks, and the completion wait does not wait for callbacks to finish. Coordinate logger shutdown separately when callbacks or buffered logs must be fully flushed.
Summary
TaskTracker gives background work a clear place in your application’s lifecycle. Register tasks, check pending work, observe failures, and wait during shutdown using an API that also fits dependency injection.
I recommend it for noncritical background operations that can tolerate failure or use a fallback. For example, I am building an Aspire project to provide on-demand ads for the Spargine Dev Tool to promote my books and speaking engagements. Once that project is complete, I plan to use TaskTracker to track downloading the latest ads. If the download is unsuccessful or the ads are not ready when needed, the tool can display cached ads or default text.
For critical operations, keep an explicit success and failure path, such as directly awaiting the task. Work that must survive process exit needs a durable mechanism; TaskTracker does not provide persistence or retries.
As always, measure before and after the change. Benchmark the operation itself and test the end-to-end tool, including shutdown time. CPU-bound work, synchronous I/O, and asynchronous I/O have different costs; scheduling and tracking add overhead, and moving work into the background does not automatically reduce total execution time. If you use TaskTracker in your projects, I would like to hear what you are tracking and how it is working for you. Suggestions for improvements are welcome.
Get Involved!
The success of open-source projects like Spargine relies on community contributions. If you find these updates useful or have ideas for further improvements, I encourage you to contribute by:
- Submitting pull requests
- Reporting issues
- Suggesting new features
Your input is invaluable in making Spargine an even more powerful tool for the .NET community.
If you are interested in contributing or have any questions, feel free to contact me via email at dotnetdave@live.com. Your support and collaboration are greatly appreciated!
Thank you, and happy coding!
Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave
© The information in this article is copyrighted and cannot be reproduced in any way without express permission from David McCarter.
Discover more from dotNetTips.com
Subscribe to get the latest posts sent to your email.

