-
-
Save dcomartin/d34a751c22bc7b9cb4de07c668eddb95 to your computer and use it in GitHub Desktop.
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 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