Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- internal class Service1
- {
- private readonly Channel<object> _channel = Channel.CreateUnbounded<object>();
- private readonly TaskCompletionSource _taskCompletionSource = new();
- public Task Completion => _taskCompletionSource.Task;
- public async Task EnqueueDataAsync(object data)
- {
- await _channel.Writer.WriteAsync(data);
- }
- public async void Start(CancellationToken ct)
- {
- try
- {
- while (await _channel.Reader.WaitToReadAsync(ct))
- {
- var item = await _channel.Reader.ReadAsync(ct);
- // ....
- }
- _taskCompletionSource.SetResult();
- }
- catch (OperationCanceledException) when (ct.IsCancellationRequested)
- {
- _taskCompletionSource.SetCanceled(ct);
- }
- catch (Exception e)
- {
- _taskCompletionSource.SetException(e);
- }
- }
- }
- internal class Service2 : BackgroundService
- {
- private readonly Channel<object> _channel = Channel.CreateUnbounded<object>();
- private readonly TaskCompletionSource _taskCompletionSource = new();
- public async Task EnqueueDataAsync(object data)
- {
- await _channel.Writer.WriteAsync(data);
- }
- protected override async Task ExecuteAsync(CancellationToken ct)
- {
- while (await _channel.Reader.WaitToReadAsync(ct))
- {
- var item = await _channel.Reader.ReadAsync(ct);
- // ....
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement