Last active
February 15, 2023 09:00
-
-
Save myarichuk/4cd44004621ec4edb54cfe949d445019 to your computer and use it in GitHub Desktop.
Lightweight Message Bus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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