public static async Task Copy <T>( this ChannelReader <T> reader, ChannelWriter <T> writer, ChannelCompletionMode channelCompletionMode, CancellationToken cancellationToken = default) { try { while (await reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false)) { while (reader.TryRead(out var value)) { await writer.WriteAsync(value, cancellationToken).ConfigureAwait(false); } } if ((channelCompletionMode & ChannelCompletionMode.PropagateCompletion) != 0) { writer.TryComplete(); } } catch (OperationCanceledException oce) { if ((channelCompletionMode & ChannelCompletionMode.PropagateCancellation) != 0) { writer.TryComplete(oce); } throw; } catch (Exception e) { if ((channelCompletionMode & ChannelCompletionMode.PropagateError) != 0) { writer.TryComplete(e); } throw; } }
private async Task WriteItemsAsync( ChannelWriter <SomeData> writer, int count, int delay, CancellationToken cancellationToken) { try { for (var i = 0; i < count; i++) { cancellationToken.ThrowIfCancellationRequested(); await writer.WriteAsync(new SomeData() { Value = i }); await Task.Delay(delay, cancellationToken); } } catch (Exception ex) { writer.TryComplete(ex); } writer.TryComplete(); }
// Transform public static async Task Transform <TIn, TOut>( this ChannelReader <TIn> reader, ChannelWriter <TOut> writer, Func <TIn, TOut> transformer, ChannelCompletionMode channelCompletionMode = ChannelCompletionMode.CompleteAndPropagateError, CancellationToken cancellationToken = default) { try { while (await reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false)) { if (reader.TryRead(out var item)) { var newItem = transformer.Invoke(item); await writer.WriteAsync(newItem, cancellationToken).ConfigureAwait(false); } } if ((channelCompletionMode & ChannelCompletionMode.Complete) != 0) { writer.TryComplete(); } } catch (OperationCanceledException) { throw; } catch (Exception e) { if (channelCompletionMode == ChannelCompletionMode.CompleteAndPropagateError) { writer.TryComplete(e); } else { throw; } } }
public static void PostToChannel <T>(this IAsyncEnumerable <T> asyncEnumerable, ChannelWriter <T> channelWriter, CancellationToken cancellationToken = default) { async Task RunPostToChannel() { try { await foreach (var item in asyncEnumerable.WithCancellation(cancellationToken)) { if (!channelWriter.TryWrite(item)) { await channelWriter.WriteAsync(item, cancellationToken); } } } catch (Exception ex) { channelWriter.TryComplete(ex); } finally { channelWriter.TryComplete(); } } _ = RunPostToChannel(); }
public static async Task CopyTo <T>(this IAsyncEnumerable <T> source, ChannelWriter <T> writer, ChannelCompletionMode channelCompletionMode, CancellationToken cancellationToken = default) { try { await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false)) { await writer.WriteAsync(item, cancellationToken).ConfigureAwait(false); } if ((channelCompletionMode & ChannelCompletionMode.Complete) != 0) { writer.TryComplete(); } } catch (OperationCanceledException) { throw; } catch (Exception e) { if (channelCompletionMode == ChannelCompletionMode.CompleteAndPropagateError) { writer.TryComplete(e); } else { throw; } } }
/// <summary> /// Read items from reader and write to writer /// </summary> /// <typeparam name="T">Type of the item</typeparam> /// <param name="reader">Read channel</param> /// <param name="writer">Write channel</param> /// <returns></returns> public static async Task WriteTo <T>( this ChannelReader <T> reader, ChannelWriter <T> writer) { try { while (await reader.WaitToReadAsync()) { while (reader.TryRead(out var evnt)) { while (!writer.TryWrite(evnt)) { if (!await writer.WaitToWriteAsync()) { return; } } } } // Manifest any errors in the completion task await reader.Completion; } catch (Exception ex) { writer.TryComplete(ex); } finally { // This will safely no-op if the catch block above ran. writer.TryComplete(); } }
private async Task WriteItemsAsync( ChannelWriter <int> writer, int count, int delay, CancellationToken cancellationToken) { try { for (var i = 0; i < count; i++) { // Check the cancellation token regularly so that the server will stop // producing items if the client disconnects. cancellationToken.ThrowIfCancellationRequested(); await writer.WriteAsync(i); // Use the cancellationToken in other APIs that accept cancellation // tokens so the cancellation can flow down to them. await Task.Delay(delay, cancellationToken); } } catch (Exception ex) { writer.TryComplete(ex); } writer.TryComplete(); }
private void TryComplete() { CompleteStage(); if (_isOwner) { _writer.TryComplete(); } }
public static async Task CheckPort(string target, ChannelReader <int> portChannel, ChannelWriter <int> outputWriter) { TcpClient client = new TcpClient(); //wait while channel is open while (await portChannel.WaitToReadAsync()) { while (portChannel.TryRead(out var message)) { try { client = new TcpClient(target, message); } catch { continue; } finally { try { client.Close(); } catch { } } outputWriter.TryWrite(message); } } client.Close(); client.Dispose(); outputWriter.TryComplete(); }
private async Task WriteItems(ChannelWriter <ProcessInfo[]> writer, int count, int delay) { for (var i = 0; i < count; i++) { var p1 = Process.GetProcesses(); var p2 = p1.OrderByDescending(_ => _.WorkingSet64); var p3 = p2.Select(_ => new ProcessInfo { ProcessName = _.ProcessName, WorkingSet = _.WorkingSet64, // TotalProcessorTime = _.TotalProcessorTime }); var p4 = p3.ToArray(); //var processes = Process.GetProcesses() // .OrderByDescending(p => p.TotalProcessorTime) // .Select(p => new ProcessInfo // { // ProcessName = p.ProcessName, // WorkingSet = p.WorkingSet64, // TotalProcessorTime = p.TotalProcessorTime // }).ToArray(); await writer.WriteAsync(p4); await Task.Delay(delay); } writer.TryComplete(); }
public static void TrySendOrClose <T>(this ChannelWriter <T> writer, T data) { if (!writer.TryWrite(data)) { writer.TryComplete(); } }
private static async Task ProcessStep2(ChannelReader <MyTask> reader, ChannelWriter <MyTask> writer) { var tasks = new List <Task>(); while (await reader.WaitToReadAsync()) { while (reader.TryRead(out MyTask mytask)) { var task = mytask; var t = Task.Run(async() => { task.DoStepN(2); while (await writer.WaitToWriteAsync()) { if (writer.TryWrite(task)) { break; } } }); tasks.Add(t); } if (reader.Completion.IsCompleted) { break; } } Task.WaitAll(tasks.ToArray()); writer.TryComplete(); }
private async Task WriteItemsAsync(ChannelWriter <object> writer, int delay, CancellationToken cancellationToken) { if (Connections[Context.ConnectionId]) { return; } byte errCount = 0; while (Connections.Any(s => s.Key.Equals(Context.ConnectionId))) { Connections[Context.ConnectionId] = true; try { cancellationToken.ThrowIfCancellationRequested(); await writer.WriteAsync(GetCurrentPerformanceCounter(), cancellationToken); } catch (Exception e) { if (errCount > 20) { break; } Console.WriteLine("WebSocket出现错误:" + e.Message); errCount++; } if (cancellationToken.IsCancellationRequested) { break; } await Task.Delay(delay, cancellationToken); } writer.TryComplete(); }
private async Task WriteDates(ChannelWriter <string> writer) { try { while (true) { await writer.WriteAsync(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss:fffffff")); await Task.Delay(10); } } catch (Exception ex) { writer.TryComplete(); } writer.TryComplete(); }
/// <summary> /// Read items from reader, transform and write to writer /// and optionally complete writer when reader completes /// or errors. /// </summary> /// <typeparam name="TSource">Type of the item</typeparam> /// <typeparam name="TTarget">Type of the target item</typeparam> /// <param name="reader">Read channel</param> /// <param name="writer">Write channel</param> /// <param name="transformAsync"></param> /// <param name="completeOnReaderCompletion">Complete writer on reader</param> /// <returns></returns> /// <returns></returns> public static async Task TransformAndWriteTo <TSource, TTarget>( this ChannelReader <TSource> reader, ChannelWriter <TTarget> writer, Func <TSource, Task <TTarget> > transformAsync, bool completeOnReaderCompletion = true) { try { while (await reader.WaitToReadAsync()) { while (reader.TryRead(out var evnt)) { var executionResult = await transformAsync(evnt); while (!writer.TryWrite(executionResult)) { if (!await writer.WaitToWriteAsync()) { return; } } } } // Manifest any errors in the completion task await reader.Completion; } catch (Exception ex) { if (completeOnReaderCompletion) { writer.TryComplete(ex); } throw; } finally { // This will safely no-op if the catch block above ran. if (completeOnReaderCompletion) { writer.TryComplete(); } } }
private async Task WriteDateAsync(ChannelWriter <string> writer, CancellationToken token) { try { while (true) { token.ThrowIfCancellationRequested(); await writer.WriteAsync(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff")); await Task.Delay(1, token); } } catch { writer.TryComplete(); } writer.TryComplete(); }
public async ValueTask DisposeAsync() { _writer.TryComplete(); await _consumeTask.ConfigureAwait(false); _singleFlush.Dispose(); _flushCts.Dispose(); }
private async Task WriteDateAsync(ChannelWriter <Rotation> writer, CancellationToken token) { try { while (true) { token.ThrowIfCancellationRequested(); await Task.Delay(10, token); } } catch { writer.TryComplete(); } writer.TryComplete(); }
private void StopCore() { if (Interlocked.Increment(ref _isStopRequested) == 1) { _stopCancellationTokenSource.CancelWithoutException(); _sentMessageQueueWriter.TryComplete(); } }
private async Task <bool> WriteItems(ChannelWriter <int> writer, int count, int delay) { for (var i = 0; i < count; i++) { await writer.WriteAsync(i); await Task.Delay(delay); } return(writer.TryComplete()); }
static async UniTaskVoid ConsumeAll(_Queue self, IUniTaskAsyncEnumerator <TSource> enumerator, ChannelWriter <TSource> writer) { try { while (await enumerator.MoveNextAsync()) { writer.TryWrite(enumerator.Current); } writer.TryComplete(); } catch (Exception ex) { writer.TryComplete(ex); } finally { self.channelClosed = true; await enumerator.DisposeAsync(); } }
private async Task WriteItemAsync(ChannelWriter <int> writer, int count, int delay, CancellationToken token) { try { for (var i = 0; i < count; i++) { token.ThrowIfCancellationRequested(); await writer.WriteAsync(i); await Task.Delay(delay, token); } } catch (Exception ex) { writer.TryComplete(ex); } writer.TryComplete(); }
private async Task WriteItemsAsync(ChannelWriter <object> writer, CancellationToken cancellationToken) { try { while (_isStreamRunning) { cancellationToken.ThrowIfCancellationRequested(); await writer.WriteAsync(await _piCameraService.CapturePictureAsByteArray()); await Task.Delay(100, cancellationToken); } } catch (Exception ex) { writer.TryComplete(ex); } writer.TryComplete(); }
//DelayCounter是一个流式传输方法, 它定义了一个延迟参数delay, 定义了推送数据碎片的间隔时间 //WriteItems是一个私有方法,它返回了一个Task对象 //WriteItems方法的最后一行writer.TryComplete()表明了流式传输完成 private async Task WriteItems(ChannelWriter <int> writer, int count, int delay) { for (int i = 0; i < count; i++) { await writer.WriteAsync(i); await Task.Delay(delay); } writer.TryComplete(); }
public Task ExecuteProcessingAsync(CancellationToken stoppingToken) { _mergeTask = Task.Run(async() => { try { using var cts = CancellationTokenSource.CreateLinkedTokenSource( _internalCts.Token, stoppingToken); var linkedToken = cts.Token; while (true) { linkedToken.ThrowIfCancellationRequested(); List <T> results = new List <T>(); for (var index = 0; index < _inputReaders.Count; index++) { try { var curReader = _inputReaders[index]; if (curReader != null) { var result = await curReader.ReadAsync(linkedToken).ConfigureAwait(false); results.Add(result); } } catch (ChannelClosedException) { _logger.LogWarning("Channel closed"); _inputReaders[index] = null; } } if (results.Count > 0) { if (!_outputWriter.TryWrite(results)) { _logger.LogWarning("Could not write merged result!"); } } else { break; } } } finally { _logger.LogInformation("Stopping:completing merge channel!"); //Complete the channel since nothing to be read anymore _outputWriter.TryComplete(); } }, stoppingToken); return(_mergeTask); }
private async Task DetectLongRunningTaskStatus(ChannelWriter <string> writer, Ulid grainId, int delay, CancellationToken cancellationToken) { try { using (var client = OrleansClientBuilder.CreateClient(_logger, _clusterInfo, _providerOption, new[] { typeof(IMyReminder) })) { await client.ConnectWithRetryAsync(); var grain = client.GetGrain <IMyReminder>(grainId.ToGuid()); string status; do { // Check the cancellation token regularly so that the server will stop // producing items if the client disconnects. cancellationToken.ThrowIfCancellationRequested(); status = await grain.GetCurrentStatus(); await writer.WriteAsync(status, cancellationToken); if (status == "stopped") { break; } await Task.Delay(TimeSpan.FromSeconds(delay), cancellationToken); } while (status == "running"); await client.Close(); } } catch (Exception ex) { _logger.Error(400, "Runtime error", ex); writer.TryComplete(ex); return; } writer.TryComplete(); }
private static async Task WriteStreamAsync <T>(IEnumerable <T> sequence, ChannelWriter <T> writer) { foreach (T element in sequence) { await writer.WriteAsync(element); await Task.Delay(100); } writer.TryComplete(); }
private async Task Write(ChannelWriter <SensorReading> writer, SensorReading val, CancellationToken cancellationToken) { try { await writer.WriteAsync(val, cancellationToken); } catch (Exception ex) { writer.TryComplete(ex); } }
static Action <Task> CreateCencelAction(ChannelWriter <Uri> uris, ChannelWriter <byte[]> imgs, CancellationTokenSource source) { return((t) => { uris.TryComplete(); imgs.TryComplete(); source.Cancel(); }); }
protected virtual void Dispose(bool disposing) { if (disposing && (_connection != null)) { #nullable disable _isPubSubMode = false; _pubsubSender?.TryComplete(); _pubsubSender = null; _connection.Dispose(); _connection = null; #nullable enable }