Reibsamen.Trolleybus
2.0.0
dotnet add package Reibsamen.Trolleybus --version 2.0.0
NuGet\Install-Package Reibsamen.Trolleybus -Version 2.0.0
<PackageReference Include="Reibsamen.Trolleybus" Version="2.0.0" />
<PackageVersion Include="Reibsamen.Trolleybus" Version="2.0.0" />
<PackageReference Include="Reibsamen.Trolleybus" />
paket add Reibsamen.Trolleybus --version 2.0.0
#r "nuget: Reibsamen.Trolleybus, 2.0.0"
#:package Reibsamen.Trolleybus@2.0.0
#addin nuget:?package=Reibsamen.Trolleybus&version=2.0.0
#tool nuget:?package=Reibsamen.Trolleybus&version=2.0.0
Trolleybus 
An implementation of a simple, threadsafe, in-memory message bus.
A package of the library is available on NuGet.
Documentation
This library is created in F#, but is very usable from a C# project. The examples in the documentation are in C#, but should be trivial to rework into F# for any F# developer.
I use C# record types to define bus messages; however, the type filtering was designed with F# union types in mind.
The MessageBus instance is a singleton and is accessed through a readonly static property on the class.
var bus = MessageBus.Instance;
If one does not wish to use the bus in its singleton form, it is interfaced, so injection techniques are available.
class WorksWithBus
{
private readonly IMessageBus _bus;
public WorksWithBus(IMessageBus bus)
{
_bus = bus;
}
// uses the bus
}
In the composition root, one can pass the singleton into the class.
var bus = MessageBus.Instance;
var worker = new WorksWithBus(bus);
The IMessageBus is the composite of two other interfaces, IMessageBusPublisher and IMessageBusListener. That way, one can reduce the API available for use through the injection.
class OnlyPostsToTheBus
{
private readonly IMessageBusPublisher _bus;
public OnlyPostsToTheBus(IMessageBusPublisher bus)
{
_bus = bus;
}
public void Hello()
{
_bus.Post("Hello.");
}
}
The examples in this documentation will use the singleton form for simplicity.
MessageBus also has static shortcuts for the singleton: MessageBus.Post, MessageBus.PostAsync, MessageBus.On, MessageBus.Observe, and MessageBus.AwaitNext do the same as calling them on MessageBus.Instance.
MessageBus.Post(new PrintMessage("Posted through the static shortcut."));
Basic Usage
The bus works with types for filtering. Each type is more or less a unique "channel" on the bus.
The channel is chosen by the type parameter of Post, which is the declared (compile-time) type, not the runtime type of the message, and there is no matching on inheritance. A Derived message posted through a Base variable reaches only Base handlers, and Derived handlers never see Base messages.
Define message types (struct or class, it does not matter).
public record PrintMessage(string Message);
public record ExitProcess(int ExitCode);
Posting to the bus is simple, just invoke the Post method.
MessageBus.Instance.Post(new PrintMessage("This is a message."));
PostAsync does the same and returns a ValueTask, with an optional cancellation token. If the token is already cancelled, the message is not posted.
await MessageBus.Instance.PostAsync(new PrintMessage("This is a message."), cancellationToken);
The Post method is thread-safe, so messages can be posted concurrently.
Post only queues the message and returns; handlers never run inside the Post call.
Handlers run on the thread pool, and the handlers for a message type receive messages one at a time, in the order they were queued.
All handlers of a message type run one after another, each message going through every handler before the next message starts, so a slow handler delays the others of that type.
Each message type has its own unbounded queue, and the bus has no backpressure: Post and PostAsync complete as soon as the message is queued, so a producer that outpaces its handlers grows memory.
Messages posted while a type has no subscribers are discarded later, on the dispatch thread, not inside Post. A subscriber added right after a Post (including AwaitNext) can therefore still receive that message.
Elsewhere in the codebase, there are a couple ways to listen for the messages.
The simplest being the On method.
using var subscription = MessageBus.Instance
.On<ExitProcess>(arg => System.Environment.Exit(arg.ExitCode));
There are overloads for asynchronous (via ValueTask) callbacks as well.
using var subscription = MessageBus.Instance.On<PrintMessage>(async arg =>
{
await Console.Out.WriteLineAsync(arg.Message);
});
Instead of disposing a subscription, a handler can be tied to a CancellationToken; it unsubscribes when the token is cancelled.
MessageBus.Instance.On<PrintMessage>(arg => Console.WriteLine(arg.Message), cancellationToken);
Messages can also be written to a ChannelWriter<T>. When a bounded channel is full, dispatch of that message type waits for space, so every other handler of the type waits too.
var channel = Channel.CreateUnbounded<PrintMessage>();
using var subscription = MessageBus.Instance.On(channel.Writer);
If Reactive Extensions is used, messages can be observed as well.
using var subscription = MessageBus.Instance
.Observe<PrintMessage>()
.Select(arg => $"Bus Message! -- {arg.Message}")
.Subscribe(msg => Console.WriteLine(msg));
If only the next message is needed, there is an AwaitNext extension method that asynchronously awaits the next message.
var exit = await MessageBus.Instance.AwaitNext<ExitProcess>();
System.Environment.Exit(exit.ExitCode);
There are overloads that allow for this message to be filtered.
var even = await MessageBus.Instance.AwaitNext<int>(i => i % 2 == 0);
Console.WriteLine($"Next even #: {even}");
Every AwaitNext overload also takes a CancellationToken. Cancelling it cancels the returned task and removes the subscription; an already cancelled token returns a cancelled task.
var exit = await MessageBus.Instance.AwaitNext<ExitProcess>(cancellationToken);
Mapping Messages
MapTo posts a new message for every message of a source type, and ChooseTo does the same but can skip messages. Both return a disposable that stops the mapping. MapToAsync and ChooseToAsync take a ValueTask-returning function instead.
public record LogEntry(string Text);
using var mapping = MessageBus.Instance.MapTo<PrintMessage, LogEntry>(arg => new LogEntry(arg.Message));
using var choosing = MessageBus.Instance.ChooseTo<PrintMessage, LogEntry>(arg =>
string.IsNullOrEmpty(arg.Message)
? FSharpValueOption<LogEntry>.None
: FSharpValueOption<LogEntry>.Some(new LogEntry(arg.Message)));
using var logging = MessageBus.Instance.MapToAsync<PrintMessage, LogEntry>(async arg =>
{
await Task.Yield();
return new LogEntry(arg.Message);
});
F# code can use the MessageBus module instead, which has mapTo, mapToAsync, chooseTo, and chooseToAsync functions that take an F# function and the bus last, for use in a pipeline. The MapTo and ChooseTo methods also accept plain F# lambdas.
Dead Letter Queue
It is best practice to handle exceptions in the listener callbacks; however, if any uncaught exceptions occur, one can subscribe to the observed dead letters.
using var _ = MessageBus.Instance.On<UncaughtMessageBusError>(arg => /* handle error */);
Message can be null: when the posted message was null, and when dispatch itself failed rather than a handler (see below). Check it before use.
If Reactive Extensions is used, there is an observable that can be subscribed to as well.
using var _ = MessageBus.Instance
.ObserveUncaughtHandlerErrors()
.Select(arg => arg.Error)
.Subscribe(arg => /* handle exception */);
Exceptions thrown by UncaughtMessageBusError handlers are not posted back to the bus, because that would hand them to the handler that just failed.
They raise the MessageBus.ErrorHandlerFailed event instead, on the dispatching thread. Exceptions thrown by its subscribers are ignored.
The event is also raised, with a null Message, if dispatching UncaughtMessageBusError itself fails unexpectedly.
MessageBus.ErrorHandlerFailed += (_, failure) => /* failure.Error is the error handler's exception */;
If dispatching a message type fails unexpectedly, the failure is posted as an UncaughtMessageBusError with a null Message, and dispatch for that message type starts again. Unread messages from the batch being dispatched when it failed are lost.
Changelog
2.0.0
- New package icon.
- Targets .NET 11 and FSharp.Core 11. .NET 10 is no longer supported; stay on 1.5.0 for .NET 10.
Postno longer runs handlers inside the call. Previously, aPostthat woke an idle bus could run handlers inline and keep dispatching other threads' messages before returning.- Because of that, a message posted while a type has no subscribers is no longer discarded inside
Post. A subscriber added right after thePost, includingAwaitNext, can now receive it. - An
UncaughtMessageBusErrorhandler that throws no longer loops forever. Its exception raises the newMessageBus.ErrorHandlerFailedevent instead of being posted to the bus. - Each
MessageBus.ErrorHandlerFailedsubscriber is invoked on its own, so one that throws does not stop the others from being called. - A
nullmessage reaching a throwing handler no longer stops all further delivery of that message type. Dispatch also restarts after any unexpected failure, which is reported as anUncaughtMessageBusErrorwith a nullMessage; error handlers should null-checkMessage. - A message type's dispatch also restarts when its loop is cancelled or when reporting its failure fails, and the restart always runs on the thread pool, even if the bus was first used from a UI or other custom scheduler.
- Dispatched messages are no longer kept alive by the bus's internal buffer, so they can be garbage collected once handlers finish with them.
- The package now depends on IcedTasks and no longer includes the Ply task builders (namespace
Reibsamen.Trolleybus.Tasks). Code that used those builders should reference Ply or IcedTasks directly. ValueTaskhandlers,MapTo,ChooseTo, and the dispatch loop no longer allocate when they complete synchronously.- Synchronous
MapToandChooseTomaps no longer go through any asynchronous machinery, andMapToAsync,ChooseToAsync, andAwaitNextrun each message through one state machine instead of two, which halves their allocations when a map suspends. PostAsyncno longer waits for queue space; it completes once the message is queued. Posting while handlers are behind no longer allocates per message.- When an asynchronous handler suspends partway through a batch, the rest of the batch is no longer copied.
AwaitNextwith an already cancelled token now returns a cancelled task instead of throwing.AwaitNextwith a predicate no longer runs the predicate on messages that arrive after its match, so a slow predicate no longer holds up the other handlers of that message type.- The asynchronous
MapToandChooseTooverloads, both the extension methods and the staticMessageBusmembers, are renamed toMapToAsyncandChooseToAsync. With only one shape per name, F# can pass a plain lambda without type arguments; C# callers that passed an async lambda toMapToorChooseTomust call theAsyncname. - New F#
MessageBusmodule withmapTo,mapToAsync,chooseTo, andchooseToAsyncfunctions that take the bus last for pipelines. - The static
MessageBus.MapToandMessageBus.ChooseTooverloads that took anIMessageBusargument no longer take one; they use the global bus like their other overloads. Use theMapTo/ChooseToextension methods to target a specific bus.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
- FSharp.Core (>= 11.0.0 && < 12.0.0)
- IcedTasks (>= 0.11.0 && < 1.0.0)
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 |
|---|---|---|
| 2.0.0 | 37 | 11/21/2026 |
| 1.5.0 | 98 | 1/5/2026 |
| 1.4.1 | 110 | 11/16/2024 |
| 1.4.0 | 87 | 11/16/2024 |
| 1.3.0 | 134 | 2/28/2024 |
| 1.2.0 | 310 | 7/26/2023 |
| 1.1.1 | 297 | 7/25/2023 |
| 1.1.0 | 275 | 7/24/2023 |
| 1.0.12 | 279 | 7/21/2023 |
| 1.0.11 | 279 | 7/17/2023 |
| 1.0.10 | 273 | 7/10/2023 |
| 1.0.9 | 248 | 7/10/2023 |
| 1.0.8 | 257 | 7/10/2023 |
| 1.0.7 | 269 | 7/10/2023 |
| 1.0.6 | 264 | 7/9/2023 |
| 1.0.5 | 410 | 1/24/2023 |
| 1.0.4 | 423 | 1/18/2023 |
| 1.0.3 | 425 | 1/18/2023 |
| 1.0.2 | 610 | 1/17/2023 |
| 1.0.0.1 | 438 | 1/15/2023 |