Concur 1.4.0-beta-001

This is a prerelease version of Concur.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Concur --version 1.4.0-beta-001
                    
NuGet\Install-Package Concur -Version 1.4.0-beta-001
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Concur" Version="1.4.0-beta-001" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Concur" Version="1.4.0-beta-001" />
                    
Directory.Packages.props
<PackageReference Include="Concur" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Concur --version 1.4.0-beta-001
                    
#r "nuget: Concur, 1.4.0-beta-001"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Concur@1.4.0-beta-001
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Concur&version=1.4.0-beta-001&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Concur&version=1.4.0-beta-001&prerelease
                    
Install as a Cake Tool

Concur

A lightweight C# library providing Go-inspired concurrency patterns for .NET applications.


💾 Installation

nuget

Install Concur via the NuGet Package Manager console:

Install-Package Concur

Or using the .NET CLI:

dotnet add package Concur

🧠 Core Concepts

Concur is built around three fundamental concepts from Go:

  • Goroutine: A lightweight, concurrent function. In Concur, you create one using the Go() method. It can be a synchronous action or an async task that runs in the background.
  • Channel: A typed, thread-safe queue that allows goroutines to communicate. One goroutine writes data to the channel, and another reads from it, ensuring safe data transfer without explicit locks.
  • WaitGroup: A synchronization aid that allows your code to block and wait until a collection of goroutines has finished executing.

🚀 Getting Started

To get started, add the following using directive. This static import gives you direct access to the Go() method.

using static ConcurRoutine;

1. Running a Goroutine (Go)

The Go() method immediately executes a function on a background thread without blocking the caller. This is ideal for "fire and forget" operations.

// Run a synchronous action concurrently.
Go(() => {
    Console.WriteLine("This is running in the background.");
});

// Run an async lambda concurrently.
// The calling thread is not blocked by the Task.Delay.
Go(async () => {
    Console.WriteLine("Starting async work...");
    await Task.Delay(1000);
    Console.WriteLine("Async work completed after 1 second.");
});

// The main thread continues its execution immediately.
Console.WriteLine("This message appears first!");

2. Using Channels for Communication

Channels are the best way for goroutines to communicate. The producer sends data, and the consumer receives it.

Explicit Channel Creation

For maximum clarity, you can create and manage a channel yourself.

// 1. Create a channel that will transport integers.
var channel = new DefaultChannel<int>();

// 2. Start a "producer" goroutine to write data to the channel.
// The 'writer' argument is a reference to the channel.
Go(async writer =>
{
    for (var i = 1; i <= 5; i++)
    {
        Console.WriteLine($"[Producer] Sending: {i}");
        await writer.WriteAsync(i);
        await Task.Delay(100); // Simulate work
    }

    // 3. Close the channel when done. This signals the consumer to stop.
    await writer.CompleteAsync();
}, channel);

// 4. Consume data from the channel on the main thread.
// The loop will automatically end when the channel is completed.
await foreach (var number in channel)
{
    Console.WriteLine($"[Consumer] Received: {number}");
}

Console.WriteLine("Channel consumed. Program finished.");
Implicit Channel (Shorthand)

Concur provides a convenient shorthand that creates and returns a channel for you.

// Go<T> creates and returns a readable channel.
// The lambda you provide is the producer.
var numbers = Go<int>(async writer =>
{
    for (var i = 0; i < 5; i++)
    {
        await writer.WriteAsync(i);
        await Task.Delay(100);
    }
    await writer.CompleteAsync(); // The producer must complete the channel.
});

// Consume the values just like before.
await foreach (var number in numbers)
{
    Console.WriteLine($"Received: {number}");
}
Bounded Channels

By default, channels are unbounded. You can specify a capacity to create a bounded channel. A producer writing to a full bounded channel will block asynchronously until a consumer makes space.

// Create a channel that can only hold 2 items at a time.
var numbers = Go<int>(async writer =>
{
    for (var i = 0; i < 10; i++)
    {
        Console.WriteLine($"[Producer] Writing {i}...");
        // This will 'block' if the channel has 2 unread items.
        await writer.WriteAsync(i);
        Console.WriteLine($"[Producer] Wrote {i}.");
    }
    await writer.CompleteAsync();
}, capacity: 2); // Set the buffer size

// Consumer
await foreach (var number in numbers)
{
    Console.WriteLine($"[Consumer] Read {number}.");
    await Task.Delay(500); // Simulate slow consumer
}

2. Synchronizing Goroutines with WaitGroup

A WaitGroup is used to wait for a group of goroutines to finish. You pass the WaitGroup instance to each goroutine you want to track.

Console.WriteLine("Starting multiple background jobs...");

var wg = new WaitGroup();
var results = new bool[3];

// Each call to Go(wg, ...) increments the WaitGroup counter.
// The counter is decremented automatically when the goroutine finishes.

Go(wg, async () => {
    await Task.Delay(100);
    results[0] = true;
    Console.WriteLine("Job 1 finished.");
});

Go(wg, async () => {
    await Task.Delay(500);
    results[1] = true;
    Console.WriteLine("Job 2 finished.");
});

Go(wg, async () => {
    await Task.Delay(250);
    results[2] = true;
    Console.WriteLine("Job 3 finished.");
});

// await wg.WaitAsync() blocks until the WaitGroup counter becomes zero.
await wg.WaitAsync();

Console.WriteLine("\nAll background jobs have completed!");
Console.WriteLine($"Results: {results[0]}, {results[1]}, {results[2]}");

⚠️ Error Handling

Concur provides a flexible, context-aware exception handling system that supports both global and per-operation exception handling.

using Microsoft.Extensions.Logging;
using Concur.Abstractions;
using static ConcurRoutine;

// Create a custom exception handler,
// by default Concur will use a `DefaultLoggingExceptionHandler`.
public class LoggingExceptionHandler : IExceptionHandler
{
    private readonly ILogger logger;
    
    public LoggingExceptionHandler(ILogger logger)
    {
        this.logger = logger;
    }
    
    public ValueTask HandleAsync(IExceptionContext context)
    {
        logger.LogError(context.Exception, 
            "Exception in routine {RoutineId} during {OperationName}: {Message}",
            context.RoutineId, 
            context.OperationName ?? "Unknown",
            context.Exception.Message);
        
        return ValueTask.CompletedTask;
    }
}

// Set the global default handler
var logger = loggerFactory.CreateLogger("Concur");
var options = new GoOptions
{
    ExceptionHandler = new LoggingExceptionHandler(logger),
};

// All goroutines will now use the handler specified in options
Go(() => throw new InvalidOperationException("This will be logged"), options);

🚀 Performance Consideration

Concur aims to offer a more expressive, Go-style concurrency API—not to outperform the Task Parallel Library (TPL).

Performance is nearly identical to using Task.Run and Channel<T> directly. The small overhead from WaitGroup is negligible in most cases.

Below is a benchmark comparing Concur (Go, DefaultChannel, WaitGroup) with idiomatic C# (Task.Run, System.Threading.Channels.Channel, Task.WhenAll):

Benchmark Results


🤝 Contributing

Contributions are welcome! If you'd like to help improve Concur, please feel free to fork the repository, make changes, and submit a pull request.


📜 License

This project is licensed under the MIT License. See the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net8.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.4.0-beta-002 165 7/27/2025
1.4.0-beta-001 255 7/26/2025
1.3.0 96 7/12/2025
1.2.0 128 7/8/2025
1.1.1 125 7/7/2025
1.1.0 129 7/7/2025
1.0.1 130 7/7/2025
1.0.0 133 7/7/2025

Introduce operator overloading for IChannel.