Skip to content

Instantly share code, notes, and snippets.

@myarichuk
Last active February 15, 2023 09:00
Show Gist options
  • Save myarichuk/4cd44004621ec4edb54cfe949d445019 to your computer and use it in GitHub Desktop.
Save myarichuk/4cd44004621ec4edb54cfe949d445019 to your computer and use it in GitHub Desktop.
Lightweight Message Bus
using namespace System.Threading.Channels;
public class MessageBus<T>
{
private readonly Channel<T> channel = Channel.CreateUnbounded<T>();
public void Subscribe(Action<T> handler)
{
var reader = channel.Reader;
Task.Run(async () =>
{
while (await reader.WaitToReadAsync())
{
while (reader.TryRead(out var item))
{
handler(item);
}
}
});
}
public async Task PublishAsync(T message)
{
await channel.Writer.WriteAsync(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment