public static async Task WaitForErrorAsync(this IHaveErrorTask provider, CancellationToken ct) { using var cts = new CancellationTokenTaskSource <object>(ct); var completedTask = await Task.WhenAny(cts.Task, provider.ErrorTask); await completedTask; // Actually throws the exception. }
public static async Task WaitForErrorAsync(this IEnumerable <IHaveErrorTask> providers, CancellationToken ct) { // NB: Every single task here is guaranteed to be faulted with an exception. // Therefore we don't need to wait for all tasks to complete. The first completed task will do. using var cts = new CancellationTokenTaskSource <object>(ct); await await Task.WhenAny(providers.Select(p => p.ErrorTask).Append(cts.Task)); }
/// <summary> /// Reads the line asynchronously and considers the <see cref="CancellationToken"/>. /// </summary> /// <param name="reader">The reader.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The read line or <c>null</c>.</returns> public static async Task <string?> ReadLineAsync(this TextReader reader, CancellationToken cancellationToken) { using var taskSource = new CancellationTokenTaskSource <string?>(cancellationToken); var result = await await Task.WhenAny(taskSource.Task, reader.ReadLineAsync()); return(result); }
public override async Task Listen(Subscription subscription, IServerStreamWriter <Message> responseStream, ServerCallContext context) { ITopicFilter topicFilter = _topicFilterFactory(subscription); _lookup.Add(responseStream, subscription, topicFilter); try { using (CancellationTokenTaskSource <object> cancellationTokenTaskSource = new CancellationTokenTaskSource <object>(context.CancellationToken)) { await Task .WhenAny(_cancellationTaskSource.Task, cancellationTokenTaskSource.Task) .ConfigureAwait(false); } } catch (Exception exception) { _logger.LogError(exception, "Error while writing messages to stream with subscription: {0}; {1}; {2}", subscription.Topic, subscription.Group, subscription.HashBy); } finally { _lookup.Remove(responseStream); } }
public void Constructor_AlreadyCanceledToken_TaskReturnsSynchronouslyCanceledTask() { var token = new CancellationToken(true); using (var source = new CancellationTokenTaskSource <object>(token)) Assert.True(source.Task.IsCanceled); }
public void Task_is_immediately_canceled() { var token = new CancellationToken(true); using var source = new CancellationTokenTaskSource <object>(token); Assert.True(source.Task.IsCanceled); }
public Task Process(Task proc, CancellationTokenSource cts = null) { // if no cancellation token passed in, just generate a dummy one and toss it if (cts == null) { cts = new CancellationTokenSource(); } var ctts = new CancellationTokenTaskSource <bool>(cts.Token); processes.Add(proc); return(Task.WhenAny(proc, ctts.Task)); }
public Task Timeout(uint duration, CancellationTokenSource cts = null) { // if no cancellation token passed in, just generate a dummy one and toss it if (cts == null) { cts = new CancellationTokenSource(); } var tcs = new TaskCompletionSource <bool>(); timeouts[tcs] = CurrentTime + duration; var ctts = new CancellationTokenTaskSource <bool>(cts.Token); return(Task.WhenAny(tcs.Task, ctts.Task).ContinueWith(task => timeouts.Remove(tcs), TaskContinuationOptions.ExecuteSynchronously)); // todo: refactor/cleanup wiht CheckTimeouts }
public async Task Test1() { var cts = new CancellationTokenSource(); cts.Cancel(); var ctts = new CancellationTokenTaskSource(cts.Token); try { await ctts.Task; } catch (OperationCanceledException ex) { Assert.Equal(cts.Token, ex.CancellationToken); } }
public static async Task WaitForReadyAsync(this IEnumerable <IHaveReadyTask> providers, CancellationToken ct) { using var cts = new CancellationTokenTaskSource <object>(ct); var tasks = providers.Select(p => p.ReadyTask).Append(cts.Task).ToList(); // Wait until all the tasks have completed, immediately throwing an // exception if any of the tasks fails. The cancellation task will be the // last task remaining, if it is not cancelled, so we wait for all but the // last task to complete. while (tasks.Count > 1) { // the required exception throwing immediacy is the reason we dont use await Task.WhenAll var completedTask = await Task.WhenAny(tasks); await completedTask; // throws the exception if it exists (including OperationCanceledException from the cancellation token) tasks.Remove(completedTask); } }
public async Task Task_completes_after_expected_time() { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1)); using var source = new CancellationTokenTaskSource <object>(cts.Token); bool canceled = false; try { await source.Task; } catch (TaskCanceledException) { canceled = true; } Assert.True(canceled); }
private async Task <IPEndPoint[]> PollAsync() { Console.Out.WriteLine("Poll"); List <UdpReceiveResult> receives = new List <UdpReceiveResult>(); using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(_queryTimeout)) using (CancellationTokenTaskSource <object> tokenTaskSource = new CancellationTokenTaskSource <object>(cancellationTokenSource.Token)) { while (!cancellationTokenSource.IsCancellationRequested) { Task <UdpReceiveResult> receiveTask = _udpClient.ReceiveAsync(); await _udpClient .SendAsync(_clusterNameBytes, _clusterNameBytes.Length, "255.255.255.255", _port) .ConfigureAwait(false); await Task .WhenAny(tokenTaskSource.Task, receiveTask) .ConfigureAwait(false); if (cancellationTokenSource.IsCancellationRequested) { break; } UdpReceiveResult recvBuffer = await receiveTask.ConfigureAwait(false); receives.Add(recvBuffer); } } return(receives .Where(udpReceiveResult => udpReceiveResult.Buffer.SequenceEqual(_clusterNameBytes)) .Select(udpReceiveResult => udpReceiveResult.RemoteEndPoint) .Distinct() .ToArray()); }
public static async Task WaitForReadyAsync(this IHaveReadyTask provider, CancellationToken ct) { using var cts = new CancellationTokenTaskSource <object>(ct); await await Task.WhenAny(cts.Task, provider.ReadyTask); }