public static Task<DownloadApplicationCompletedEventArgs> DownloadApplicationAsync(this InPlaceHostingManager manager, Action<DownloadProgressChangedEventArgs> callback = null) { var tcs = new TaskCompletionSource<DownloadApplicationCompletedEventArgs>(); manager.DownloadProgressChanged += (sender, e) => { try { callback(e); } catch(Exception) { manager.CancelAsync(); } }; manager.DownloadApplicationCompleted += (sender, e) => { if(e.Error != null) { tcs.SetException(e.Error); return; } tcs.SetResult(e); }; manager.DownloadApplicationAsync(); return tcs.Task; }
/// <summary> /// Asynchronously downloads the resource as a String from the URI specified, /// and monitors cancellation requests, and reports progress. /// </summary> /// <param name="webClient">The WebClient which will be used to dowload.</param> /// <param name="address">The URI of the resource to download.</param> /// <param name="token">The token to monitor for cancellation requests. The default value is None.</param> /// <param name="progress">An object that receives progress updates.</param> /// <returns>The task object representing the asynchronous operation. The Result property on the task object returns a string result of the operation.</returns> public static Task<String> DownloadStringTaskAsync(this WebClient webClient, Uri address, CancellationToken token, IProgress<DownloadProgressChangedEventArgs> progress) { if (webClient == null) throw new NullReferenceException(); var tcs = new TaskCompletionSource<string>(); if (token != CancellationToken.None) token.Register(() => webClient.CancelAsync()); DownloadProgressChangedEventHandler progressHandler = null; if (progress != null) { progressHandler = (sender, e) => progress.Report(e); webClient.DownloadProgressChanged += progressHandler; } DownloadStringCompletedEventHandler handler = null; handler = (sender, e) => { if (progress != null) webClient.DownloadProgressChanged -= progressHandler; webClient.DownloadStringCompleted -= handler; if (e.Error != null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(e.Result); }; webClient.DownloadStringCompleted += handler; try { webClient.DownloadStringAsync(address); } catch { webClient.DownloadProgressChanged -= progressHandler; webClient.DownloadStringCompleted -= handler; throw; } return tcs.Task; }
/// <summary> /// Cancel a currently running template deployment. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> CancelAsync(this IDeploymentOperations operations, string resourceGroupName, string deploymentName) { return operations.CancelAsync(resourceGroupName, deploymentName, CancellationToken.None); }
/// <summary> /// Asynchronously downloads the resource with the specified URI as a Byte array limited by the specified timeout and allows cancelling the operation. /// </summary> /// <param name="client">The client with which to download the specified resource.</param> /// <param name="address">The address of the resource to download.</param> /// <param name="timeout">A TimeSpan specifying the amount of time to wait for a response before aborting the request. /// The specify an infinite timeout, pass a TimeSpan with a TotalMillisecond value of Timeout.Infinite. /// When a request is aborted due to a timeout the returned task will transition to the Faulted state with a TimeoutException.</param> /// <param name="token">A cancellation token that can be used to cancel the pending asynchronous task.</param> /// <returns>A Task with the future value of the downloaded string.</returns> /// <exception cref="ArgumentNullException">Thrown when a null value is passed to the client or address parameters.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when the value of timeout is neither a positive value or infinite.</exception> public static Task<byte[]> DownloadDataTaskAsync(this WebClient client, Uri address, TimeSpan timeout, CancellationToken token) { if (client == null) throw new ArgumentNullException("client"); if (address == null) throw new ArgumentNullException("address"); if (timeout.TotalMilliseconds < 0 && timeout != InfiniteTimeout) throw new ArgumentOutOfRangeException("address", timeout, "The timeout value must be a positive or equal to InfiniteTimeout."); if (token.IsCancellationRequested) return PreCancelledTask; var tcs = new TaskCompletionSource<byte[]>(); var delayTokenSource = new CancellationTokenSource(); if (timeout != InfiniteTimeout) { Task.Factory.Delay(timeout, delayTokenSource.Token).ContinueWith(t => { tcs.TrySetException(new TimeoutException(string.Format("The request has exceeded the timeout limit of {0} and has been aborted.", timeout))); client.CancelAsync(); }, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled); } DownloadDataCompletedEventHandler completedHandler = null; completedHandler = (sender, args) => { client.DownloadDataCompleted -= completedHandler; delayTokenSource.Cancel(); if (args.Cancelled) tcs.TrySetCanceled(); else if (args.Error != null) tcs.TrySetException(args.Error); else tcs.TrySetResult(args.Result); }; client.DownloadDataCompleted += completedHandler; try { client.DownloadDataAsync(address); } catch { client.DownloadDataCompleted -= completedHandler; throw; } token.Register(() => { delayTokenSource.Cancel(); client.CancelAsync(); }); return tcs.Task; }
/// <summary> /// Asynchronously downloads the resource with the specified URI as a Byte array limited by the specified timeout and allows cancelling the operation. /// </summary> /// <param name="webClient">The client with which to download the specified resource.</param> /// <param name="uri">The address of the resource to download.</param> /// <param name="timeout">A TimeSpan specifying the amount of time to wait for a response before aborting the request. /// The specify an infinite timeout, pass a TimeSpan with a TotalMillisecond value of Timeout.Infinite. /// When a request is aborted due to a timeout the returned task will transition to the Faulted state with a TimeoutException.</param> /// <param name="token">A cancellation token that can be used to cancel the pending asynchronous task.</param> /// <returns>A Task with the future value of the downloaded string.</returns> /// <exception cref="ArgumentNullException">Thrown when a null value is passed to the client or address parameters.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when the value of timeout is neither a positive value or infinite.</exception> public static Task<byte[]> DownloadDataTaskAsync(this WebClient webClient, Uri uri, TimeSpan timeout, CancellationToken token) { if (webClient == null) throw new ArgumentNullException(nameof(webClient)); if (uri == null) throw new ArgumentNullException(nameof(uri)); if (timeout.TotalMilliseconds < 0 && timeout != DefaultTimeout) throw new ArgumentOutOfRangeException(nameof(uri), timeout, "The timeout value must be a positive or equal to InfiniteTimeout."); if (token.IsCancellationRequested) return PreCancelledTask; var taskCompletionSource = new TaskCompletionSource<byte[]>(); var cancellationTokenSource = new CancellationTokenSource(); if (timeout != DefaultTimeout) { Task.Delay(timeout, cancellationTokenSource.Token).ContinueWith(x => { taskCompletionSource.TrySetException(new TimeoutException($"The request has exceeded the timeout limit of {timeout} and has been aborted.")); webClient.CancelAsync(); }, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled); } DownloadDataCompletedEventHandler completedHandler = null; completedHandler = (sender, args) => { webClient.DownloadDataCompleted -= completedHandler; cancellationTokenSource.Cancel(); if (args.Cancelled) { taskCompletionSource.TrySetCanceled(); } else if (args.Error != null) { taskCompletionSource.TrySetException(args.Error); } else { taskCompletionSource.TrySetResult(args.Result); } }; webClient.DownloadDataCompleted += completedHandler; try { webClient.DownloadDataAsync(uri); } catch { webClient.DownloadDataCompleted -= completedHandler; throw; } token.Register(() => { cancellationTokenSource.Cancel(); webClient.CancelAsync(); }); return taskCompletionSource.Task; }
/// <summary> /// Cancel a pending upgrade for the Azure SQL Database server. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerUpgradeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server to cancel /// upgrade. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> CancelAsync(this IServerUpgradeOperations operations, string resourceGroupName, string serverName) { return operations.CancelAsync(resourceGroupName, serverName, CancellationToken.None); }
/// <summary> /// Cancel the job. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Job ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> CancelAsync(this IJobOperations operations, string jobId, CustomRequestHeaders customRequestHeaders) { return operations.CancelAsync(jobId, customRequestHeaders, CancellationToken.None); }
/// <summary> /// Asynchronously downloads the resource with the specified URI as a Byte array limited by the specified timeout and allows cancelling the operation. /// </summary> /// <param name="_client">The client with which to download the specified resource.</param> /// <param name="_address">The address of the resource to download.</param> /// <param name="_timeout">A TimeSpan specifying the amount of time to wait for a response before aborting the request. /// The specify an infinite timeout, pass a TimeSpan with a TotalMillisecond value of Timeout.Infinite. /// When a request is aborted due to a timeout the returned task will transition to the Faulted state with a TimeoutException.</param> /// <param name="_token">A cancellation token that can be used to cancel the pending asynchronous task.</param> /// <returns>A Task with the future value of the downloaded string.</returns> /// <exception cref="ArgumentNullException">Thrown when a null value is passed to the client or address parameters.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when the value of timeout is neither a positive value or infinite.</exception> public static Task<byte[]> DownloadDataTaskAsync(this WebClient _client, Uri _address, TimeSpan _timeout, CancellationToken _token) { if (_client == null) throw new ArgumentNullException("_client"); if (_address == null) throw new ArgumentNullException("_address"); if (_timeout.TotalMilliseconds < 0 && _timeout != _infiniteTimeout) throw new ArgumentOutOfRangeException("_address", _timeout, "The timeout value must be a positive or equal to InfiniteTimeout."); if (_token.IsCancellationRequested) return _preCancelledTask; var _tcs = new TaskCompletionSource<byte[]>(); var _delayTokenSource = new CancellationTokenSource(); if (_timeout != _infiniteTimeout) { Task.Delay(_timeout, _delayTokenSource.Token).ContinueWith(_t => { _tcs.TrySetException(new TimeoutException(string.Format("The request has exceeded the timeout limit of {0} and has been aborted.", _timeout))); _client.CancelAsync(); }, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled); } DownloadDataCompletedEventHandler _completedHandler = null; _completedHandler = (_sender, _args) => { _client.DownloadDataCompleted -= _completedHandler; _delayTokenSource.Cancel(); if (_args.Cancelled) _tcs.TrySetCanceled(); else if (_args.Error != null) _tcs.TrySetException(_args.Error); else _tcs.TrySetResult(_args.Result); }; _client.DownloadDataCompleted += _completedHandler; try { _client.DownloadDataAsync(_address); } catch { _client.DownloadDataCompleted -= _completedHandler; throw; } _token.Register(() => { _delayTokenSource.Cancel(); _client.CancelAsync(); }); return _tcs.Task; }
/// <summary> /// Cancels the running job specified by the job ID. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataLake.AnalyticsJob.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the Data Lake Analytics account to cancel the /// job for /// </param> /// <param name='jobIdentity'> /// Required. JobInfo ID to cancel. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> CancelAsync(this IJobOperations operations, string resourceGroupName, string accountName, Guid jobIdentity) { return operations.CancelAsync(resourceGroupName, accountName, jobIdentity, CancellationToken.None); }
/// <summary> /// /// </summary> /// <param name="webClient">The WebClient which will be used to dowload.</param> /// <param name="address"></param> /// <param name="method"></param> /// <param name="data"></param> /// <param name="userToken">A user-defined object that is passed to the method invoked when the asynchronous operation completes.</param> /// <param name="token">The token to monitor for cancellation requests. The default value is None.</param> /// <param name="progress">An object that receives progress updates.</param> /// <returns></returns> public static Task<Tuple<string, object>> UploadStringTaskAsync(this WebClient webClient, Uri address, string method, string data, object userToken, CancellationToken token, IProgress<UploadProgressChangedEventArgs> progress) { if (webClient == null) throw new NullReferenceException(); var tcs = new TaskCompletionSource<Tuple<string, object>>(); if (token != CancellationToken.None) token.Register(() => webClient.CancelAsync()); UploadProgressChangedEventHandler progressHandler = null; if (progress != null) progressHandler = (sender, e) => progress.Report(e); UploadStringCompletedEventHandler handler = null; handler = (sender, e) => { if (progress != null) webClient.UploadProgressChanged -= progressHandler; webClient.UploadStringCompleted -= handler; if (e.Error != null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(Tuple.Create(e.Result, userToken)); }; webClient.UploadProgressChanged += progressHandler; webClient.UploadStringCompleted += handler; try { webClient.UploadStringAsync(address, method, data, userToken); } catch { webClient.UploadProgressChanged -= progressHandler; webClient.UploadStringCompleted -= handler; throw; } return tcs.Task; }
/// <summary> /// Opens a stream for writing data to the specified resource, using the specified method, as an asynchronous operation using a task object. /// </summary> /// <param name="webClient">The WebClient which will be used to dowload.</param> /// <param name="address">The URI of the resource to receive the data.</param> /// <param name="method">The method used to send the data to the resource. If null, the default is POST for http and STOR for ftp.</param> /// <param name="userToken">A user-defined object that is passed to the method invoked when the asynchronous operation completes.</param> /// <param name="token">The token to monitor for cancellation requests. The default value is None.</param> /// <returns></returns> public static Task<Tuple<Stream, object>> OpenWriteTaskAsync(this WebClient webClient, Uri address, string method, object userToken, CancellationToken token) { if (webClient == null) throw new NullReferenceException(); var tcs = new TaskCompletionSource<Tuple<Stream, object>>(); if (token != CancellationToken.None) token.Register(() => webClient.CancelAsync()); OpenWriteCompletedEventHandler handler = null; handler = (sender, e) => { webClient.OpenWriteCompleted -= handler; if (e.Error != null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(Tuple.Create(e.Result, userToken)); }; webClient.OpenWriteCompleted += handler; try { webClient.OpenWriteAsync(address, method, userToken); } catch { webClient.OpenWriteCompleted -= handler; throw; } return tcs.Task; }
/// <summary> /// Opens a stream for writing data to the specified resource as an asynchronous operation using a task object. /// </summary> /// <param name="webClient">The WebClient which will be used to dowload.</param> /// <param name="address">The URI of the resource to receive the data.</param> /// <param name="token">The token to monitor for cancellation requests. The default value is None.</param> /// <returns></returns> public static Task<Stream> OpenWriteTaskAsync(this WebClient webClient, Uri address, CancellationToken token) { if (webClient == null) throw new NullReferenceException(); var tcs = new TaskCompletionSource<Stream>(); if (token != CancellationToken.None) token.Register(() => webClient.CancelAsync()); OpenWriteCompletedEventHandler handler = null; handler = (sender, e) => { webClient.OpenWriteCompleted -= handler; if (e.Error != null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(e.Result); }; webClient.OpenWriteCompleted += handler; webClient.OpenWriteAsync(address); return tcs.Task; }
public static void CancelAsyncExt(this BackgroundWorker bw) { bw.CancelAsync(); }