private static async Task UseEnumeratorAsync() { var aDevice = new ADevice(); await foreach (var x in aDevice.GetSensorData1()) { Console.WriteLine($"{x.Value1} {x.Value2}"); } }
private static async Task WhileLoopAsync() { var aDevice = new ADevice(); IAsyncEnumerable <SensorData> dataStream = aDevice.GetSensorData1(); await using IAsyncEnumerator <SensorData> enumerator = dataStream.GetAsyncEnumerator(); while (await enumerator.MoveNextAsync()) { var sensorData = enumerator.Current; Console.WriteLine($"{sensorData.Value1} {sensorData.Value2}"); } }
static async Task Main() { var aDevice = new ADevice(); await foreach (var x in aDevice.GetSensorData1()) { Console.WriteLine($"{x.Value1} {x.Value2}"); } //var cts = new CancellationTokenSource(); //cts.CancelAfter(5000); //var aDevice = new ADevice(); //await foreach(var x in aDevice.GetSensorData(cts.Token)) //{ // Console.WriteLine($"{x.Value1} {x.Value2}"); //} Console.WriteLine("finished"); }
private static async Task AsyncStreamWithCancellation() { var cts = new CancellationTokenSource(); cts.Token.Register(() => Console.WriteLine("cancellation requested")); cts.CancelAfter(5000); try { var aDevice = new ADevice(); await foreach (var x in aDevice.GetSensorData1(cts.Token)) //.WithCancellation(cts.Token)) { Console.WriteLine($"{x.Value1} {x.Value2}"); } } catch (OperationCanceledException ex) { Console.WriteLine(ex.Message); } }
private static async Task Demo2Async() { var aDevice = new ADevice(); IAsyncEnumerable <SensorData> en = aDevice.GetSensorData1(); IAsyncEnumerator <SensorData> enumerator = en.GetAsyncEnumerator(); try { while (await enumerator.MoveNextAsync()) { var sensorData = enumerator.Current; Console.WriteLine($"{sensorData.Value1} {sensorData.Value2}"); } } finally { await enumerator.DisposeAsync(); } }