public virtual Task <IRestResponse> ExecuteTaskAsync(IRestRequest request, CancellationToken token) { if (request == null) { throw new ArgumentNullException("request"); } TaskCompletionSource <IRestResponse> taskCompletionSource = new TaskCompletionSource <IRestResponse>(); try { RestRequestAsyncHandle async = ExecuteAsync(request, delegate(IRestResponse response, RestRequestAsyncHandle _) { if (token.IsCancellationRequested) { taskCompletionSource.TrySetCanceled(); } else { taskCompletionSource.TrySetResult(response); } }); token.Register(delegate { async.Abort(); taskCompletionSource.TrySetCanceled(); }); } catch (Exception exception) { taskCompletionSource.TrySetException(exception); } return(taskCompletionSource.Task); }
/// <summary> /// Executes the request asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> /// <param name="token">The cancellation token</param> public virtual Task <IRestResponse> ExecuteTaskAsync(IRestRequest request, CancellationToken token) { if (request == null) { throw new ArgumentNullException("request"); } TaskCompletionSource <IRestResponse> taskCompletionSource = new TaskCompletionSource <IRestResponse>(); try { RestRequestAsyncHandle async = this.ExecuteAsync( request, (response, _) => { if (token.IsCancellationRequested) { taskCompletionSource.TrySetCanceled(); } // Don't run TrySetException, since we should set Error // properties and swallow exceptions to be consistent // with sync methods else { taskCompletionSource.TrySetResult(response); } }); #if !WINDOWS_PHONE CancellationTokenRegistration registration = #endif token.Register(() => { async.Abort(); taskCompletionSource.TrySetCanceled(); }); #if !WINDOWS_PHONE taskCompletionSource.Task.ContinueWith(t => registration.Dispose(), token); #endif } catch (Exception ex) { taskCompletionSource.TrySetException(ex); } return(taskCompletionSource.Task); }