Advertisement
Guest User

Untitled

a guest
Apr 16th, 2022
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.69 KB | None | 0 0
  1. internal class Service1
  2.     {
  3.         private readonly Channel<object> _channel = Channel.CreateUnbounded<object>();
  4.         private readonly TaskCompletionSource _taskCompletionSource = new();
  5.  
  6.         public Task Completion => _taskCompletionSource.Task;
  7.  
  8.         public async Task EnqueueDataAsync(object data)
  9.         {
  10.             await _channel.Writer.WriteAsync(data);
  11.         }
  12.  
  13.         public async void Start(CancellationToken ct)
  14.         {
  15.             try
  16.             {
  17.                 while (await _channel.Reader.WaitToReadAsync(ct))
  18.                 {
  19.                     var item = await _channel.Reader.ReadAsync(ct);
  20.                     // ....
  21.                 }
  22.  
  23.                 _taskCompletionSource.SetResult();
  24.             }
  25.             catch (OperationCanceledException) when (ct.IsCancellationRequested)
  26.             {
  27.                 _taskCompletionSource.SetCanceled(ct);
  28.             }
  29.             catch (Exception e)
  30.             {
  31.                 _taskCompletionSource.SetException(e);
  32.             }
  33.         }
  34.     }
  35.  
  36.     internal class Service2 : BackgroundService
  37.     {
  38.         private readonly Channel<object> _channel = Channel.CreateUnbounded<object>();
  39.         private readonly TaskCompletionSource _taskCompletionSource = new();
  40.        
  41.         public async Task EnqueueDataAsync(object data)
  42.         {
  43.             await _channel.Writer.WriteAsync(data);
  44.         }
  45.  
  46.         protected override async Task ExecuteAsync(CancellationToken ct)
  47.         {
  48.             while (await _channel.Reader.WaitToReadAsync(ct))
  49.             {
  50.                 var item = await _channel.Reader.ReadAsync(ct);
  51.                 // ....
  52.             }
  53.         }
  54.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement