Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Last active June 26, 2025 21:10
Show Gist options
  • Select an option

  • Save dcomartin/d34a751c22bc7b9cb4de07c668eddb95 to your computer and use it in GitHub Desktop.

Select an option

Save dcomartin/d34a751c22bc7b9cb4de07c668eddb95 to your computer and use it in GitHub Desktop.
using System.Threading.Channels;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddLogging();
builder.Services.AddSingleton<Channel<Ping>>(x => Channel.CreateUnbounded<Ping>(new UnboundedChannelOptions { SingleReader = true }));
builder.Services.AddHostedService<Consumer>();
builder.WebHost.UseUrls("http://localhost:5050");
builder.Logging.AddConsole();
var app = builder.Build();
app.MapGet("/test", async (Channel<Ping> channel) =>
{
await channel.Writer.WriteAsync(new Ping("CodeOpinion"));
return "OK";
});
await app.RunAsync();
public record Ping(string Message);
public class Consumer : IHostedService
{
private readonly Channel<Ping> _channel;
public Consumer(Channel<Ping> channel)
{
_channel = channel;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
while (await _channel.Reader.WaitToReadAsync(cancellationToken))
{
var item = await _channel.Reader.ReadAsync(cancellationToken);
Console.WriteLine($"Consumed: {item.Message}");
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment