static void Main(string[] args) { var sink = new DataSink(); for (int i = 0; i < 3; i++) { GenerateItemsAsync(i, sink); } Console.ReadLine(); }
static async void GenerateItemsAsync(int id, DataSink sink) { var random = new Random(id); while (true) { int number = random.Next(1000); await Task.Delay(TimeSpan.FromMilliseconds(number)); sink.Enqueue($"{id}: {number}"); } }
static void Main(string[] args) { var cts = new CancellationTokenSource(); using (var sink = new DataSink("sample.txt")) { var task = Task.WhenAll(from id in Enumerable.Range(0, 3) select GenerateItemsAsync(id, sink, cts.Token)); Console.ReadLine(); cts.Cancel(); task.Wait(); } }
static void Main(string[] args) { using (var sink = new DataSink("sample.txt")) { for (int i = 0; i < 3; i++) { GenerateItemsAsync(i, sink); } Console.ReadLine(); sink.DrainAsync().Wait(); } }
static async Task Test(CancellationToken ct) { using (var sink = new DataSink("sample.txt")) { var sources = from id in Enumerable.Range(0, 3) select Observable.Create <string>( observer => GenerateAsync(observer, id, ct)); var tcs = new TaskCompletionSource <object>(); Observable .Merge(sources) .Finally(() => tcs.SetResult(null)) .Subscribe(sink.PutData); await tcs.Task; } }
static async Task GenerateItemsAsync(int id, DataSink sink, CancellationToken ct) { try { var random = new Random(id); while (true) { int number = random.Next(1000); await Task.Delay(TimeSpan.FromMilliseconds(number), ct); await sink.PutDataAsync($"{id}: {number}"); } } catch (OperationCanceledException) { // ignore } }