/// <summary> /// Wraps a task with one that will complete as cancelled based on a cancellation token, /// allowing someone to await a task but be able to break out early by cancelling the token. /// </summary> /// <typeparam name="T">The type of value returned by the task.</typeparam> /// <param name="task">The task to wrap.</param> /// <param name="cancellationToken">The token that can be canceled to break out of the await.</param> /// <returns>The wrapping task.</returns> private static async System.Threading.Tasks.Task <T> WithCancellationSlow <T>(System.Threading.Tasks.Task <T> task, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource <bool>(); using (cancellationToken.Register(s => ((TaskCompletionSource <bool>)s).TrySetResult(true), tcs)) { if (task != await System.Threading.Tasks.Task.WhenAny(task, tcs.Task).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); } } // Rethrow any fault/cancellation exception, even if we awaited above. // But if we skipped the above if branch, this will actually yield // on an incompleted task. return(await task.ConfigureAwait(false)); }
/// <summary> /// Gets the specified <see cref="CloudTask"/>. /// </summary> /// <param name="taskId">The id of the task to get.</param> /// <param name="detailLevel">A <see cref="DetailLevel"/> used for controlling which properties are retrieved from the service.</param> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/> and <paramref name="detailLevel"/>.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="CloudTask"/> containing information about the specified Azure Batch task.</returns> /// <remarks>The get task operation runs asynchronously.</remarks> public async System.Threading.Tasks.Task <CloudTask> GetTaskAsync( string taskId, DetailLevel detailLevel = null, IEnumerable <BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // throw if if this object is unbound UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState); // craft the behavior manager for this call BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors, detailLevel); using (System.Threading.Tasks.Task <CloudTask> asyncTask = this.parentBatchClient.JobOperations.GetTaskAsyncImpl(this.Id, taskId, bhMgr, cancellationToken)) { CloudTask theTask = await asyncTask.ConfigureAwait(continueOnCapturedContext : false); return(theTask); } }