public Task ReturnFile(IDictionary<string, object> env) { var tcs = new TaskCompletionSource<int>(); if (env.GetPath().ToLower().Equals("/index.html", StringComparison.CurrentCultureIgnoreCase)) { try { env["owin.ResponseHeaders"] = new Dictionary<string, string[]> { { "Content-Type", new[] {"text/html"} } }; HandleRequest(env); env["owin.ResponseStatusCode"] = 200; tcs.SetResult(0); } catch (Exception ex) { Trace.TraceError(ex.Message); tcs.SetCanceled(); } } else { tcs.SetCanceled(); } return tcs.Task; }
public Task Hide(bool close) { m_Wait?.SetCanceled(); StopAllCoroutines(); m_Animator.SetBool("OPEN", false); m_Animator.SetBool("SHOW", false); m_Animator.SetBool("CLOSE", close); m_Animator.SetBool("HIDE", true); m_WaitState = "HIDE"; m_Wait = new TaskCompletionSource <bool>(); StartCoroutine(Wait()); return(m_Wait.Task); }
public static Task<string> QuestionAsync(string title, string question, Func<string,string> validator = null, string defaultAnswer = "") { var dataContext = new InputModel { Title = title, Message = question, ValidationCallback = validator, }; dataContext.SetDefaultAnswer(defaultAnswer); var inputWindow = new InputWindow { DataContext = dataContext }; var tcs = new TaskCompletionSource<string>(); inputWindow.Closed += (sender, args) => { if (inputWindow.DialogResult == true) tcs.SetResult(dataContext.Answer); else tcs.SetCanceled(); }; inputWindow.Show(); return tcs.Task; }
public Task<IEnumerable<Song>> GetSongs(string query, CancellationToken cancellationToken) { var result = MemoryCache.Default.Get(query) as IEnumerable<Song>; if (result != null) { return Task.Factory.StartNew(() => result); } var tcs = new TaskCompletionSource<IEnumerable<Song>>(); _provider .GetSongs(query, cancellationToken) .ContinueWith(t => { if (t.IsFaulted) { tcs.SetException(t.Exception); } else if (t.IsCanceled) { tcs.SetCanceled(); } else { MemoryCache.Default.Set(query, t.Result, new CacheItemPolicy { SlidingExpiration = SlidingExpiration }); tcs.SetResult(t.Result); } }); return tcs.Task; }
public static Task AlertUser(string title, string message) { var dataContext = new ConfirmModel { Title = title, Message = message, AllowCancel = false, }; var inputWindow = new ConfirmWindow() { DataContext = dataContext }; var tcs = new TaskCompletionSource<bool>(); inputWindow.Closed += (sender, args) => { if (inputWindow.DialogResult == true) tcs.SetResult(true); else tcs.SetCanceled(); }; inputWindow.Show(); return tcs.Task; }
public void Dispose() { try { _pipelineExecutionTask?.SetCanceled(); _pipelineResultTask?.SetCanceled(); _debuggerExecutionTask?.SetCanceled(); } catch (InvalidOperationException) { } _cancellationTokenSource.Cancel(); if (_powerShell != null) { _powerShell.Dispose(); _powerShell = null; } if (_runspace != null) { _runspace.Close(); _runspace.Dispose(); _runspace = null; } if (_cachedScriptPath != null) { File.Delete(_cachedScriptPath); } }
public async Task Should_call_on_error(TransportTransactionMode transactionMode) { var onErrorCalled = new TaskCompletionSource<ErrorContext>(); OnTestTimeout(() => onErrorCalled.SetCanceled()); await StartPump(context => { throw new Exception("Simulated exception"); }, context => { onErrorCalled.SetResult(context); return Task.FromResult(ErrorHandleResult.Handled); }, transactionMode); await SendMessage(InputQueueName, new Dictionary<string, string> { { "MyHeader", "MyValue" } }); var errorContext = await onErrorCalled.Task; Assert.AreEqual(errorContext.Exception.Message, "Simulated exception", "Should preserve the exception"); Assert.AreEqual(1, errorContext.ImmediateProcessingFailures, "Should track the number of delivery attempts"); Assert.AreEqual("MyValue", errorContext.Message.Headers["MyHeader"], "Should pass the message headers"); }
public void Should_call_onBulkheadRejected_with_passed_context() { string executionKey = Guid.NewGuid().ToString(); Context contextPassedToExecute = new Context(executionKey); Context contextPassedToOnRejected = null; Action<Context> onRejected = ctx => { contextPassedToOnRejected = ctx; }; BulkheadPolicy<int> bulkhead = Policy.Bulkhead<int>(1, onRejected); TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); using (CancellationTokenSource cancellationSource = new CancellationTokenSource()) { Task.Run(() => { bulkhead.Execute(() => { tcs.Task.Wait(); return 0; }); }); Within(shimTimeSpan, () => bulkhead.BulkheadAvailableCount.Should().Be(0)); // Time for the other thread to kick up and take the bulkhead. bulkhead.Invoking(b => b.Execute(() => 1, contextPassedToExecute)).ShouldThrow<BulkheadRejectedException>(); cancellationSource.Cancel(); tcs.SetCanceled(); } contextPassedToOnRejected.Should().NotBeNull(); contextPassedToOnRejected.ExecutionKey.Should().Be(executionKey); contextPassedToOnRejected.Should().BeSameAs(contextPassedToExecute); }
public void SubscriptionWithCancelledTaskCanBeDisposed() { var dr = new DefaultDependencyResolver(); using (var bus = new MessageBus(dr)) { var subscriber = new TestSubscriber(new[] { "key" }); var wh = new ManualResetEventSlim(); IDisposable subscription = bus.Subscribe(subscriber, null, async (result, state) => { if (result.Terminal) { return false; } await Task.Delay(50); var tcs = new TaskCompletionSource<bool>(); tcs.SetCanceled(); wh.Set(); return await tcs.Task; }, 10, null); bus.Publish("me", "key", "hello"); wh.Wait(); subscription.Dispose(); } }
public static Task<Byte[]> DownloadDataTaskAsync(this WebClient client, Uri address) { var completerionSource = new TaskCompletionSource<byte[]>(); var token = new object(); OpenReadCompletedEventHandler handler = null; handler = (sender, args) => { if (args.UserState != token) { return; } if (args.Error != null) { completerionSource.SetException(args.Error); } else if (args.Cancelled) { completerionSource.SetCanceled(); } else { completerionSource.SetResult(args.Result.ToArray()); } client.OpenReadCompleted -= handler; }; client.OpenReadCompleted += handler; client.OpenReadAsync(address, token); return completerionSource.Task; }
internal TaskCompletionSource<IEdmModel> CompeteModelGeneration(out Task<IEdmModel> running) { var source = new TaskCompletionSource<IEdmModel>(TaskCreationOptions.AttachedToParent); var runningTask = Interlocked.CompareExchange(ref modelTask, source.Task, null); if (runningTask != null) { running = runningTask; source.SetCanceled(); return null; } source.Task.ContinueWith( task => { if (task.Status == TaskStatus.RanToCompletion) { Model = task.Result; } else { // Set modelTask null to allow retrying GetModelAsync. Interlocked.Exchange(ref modelTask, null); } }, TaskContinuationOptions.ExecuteSynchronously); running = null; return source; }
/// <summary> /// Return the Task for sending a <see cref="MailMessage"/> asynchronously /// </summary> /// <param name="client">The <see cref="SmtpClient"/> object to extend</param> /// <param name="message">The <see cref="MailMessage"/> to send</param> /// <returns>The <see cref="Task"/></returns> /// <remarks> /// http://stackoverflow.com/questions/15140308/how-to-send-mails-asynchronous/ /// http://stackoverflow.com/questions/3408397/asynchronously-sending-emails-in-c /// </remarks> public static Task SendAsync(this SmtpClient client, MailMessage message) { var tcs = new TaskCompletionSource<object>(); var sendGuid = Guid.NewGuid(); SendCompletedEventHandler handler = null; handler = (o, ea) => { if (!(ea.UserState is Guid) || ((Guid) ea.UserState) != sendGuid) return; client.SendCompleted -= handler; if (ea.Cancelled) { tcs.SetCanceled(); } else if (ea.Error != null) { tcs.SetException(ea.Error); } else { tcs.SetResult(null); } }; client.SendCompleted += handler; client.SendAsync(message, sendGuid); return tcs.Task; }
public void CancelledTaskShouldThrowTaskCancelledSync() { Func<MessageResult, object, Task<bool>> callback = (result, state) => { var tcs = new TaskCompletionSource<bool>(); tcs.SetCanceled(); return tcs.Task; }; var subscription = new Mock<TestSubscription>("TestSub", new[] { "a" }, callback, 1) { CallBase = true }; using (subscription.Object) { Task task = null; TestUtilities.AssertUnwrappedException<TaskCanceledException>(() => { task = subscription.Object.Work(); task.Wait(); }); Assert.True(task.IsCanceled); } }
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken) { if (type == null) { throw new ArgumentNullException("type"); } if (readStream == null) { throw new ArgumentNullException("readStream"); } var completion = new TaskCompletionSource<object>(); if (cancellationToken.IsCancellationRequested) { completion.SetCanceled(); } else { try { var value = ReadValue(type, readStream, content, formatterLogger); completion.SetResult(value); } catch (Exception ex) { completion.SetException(ex); } } return completion.Task; }
public Task<Address_Validated> Automatically_Validate_Address(string textAddress) { var tcs = new TaskCompletionSource<Address_Validated>(); var geocoding = maps.ServiceHelper.GetGeocodeService(); geocoding.GeocodeCompleted += (sender, e) => { //if (e.Error != null) // tcs.SetCanceled(); if (e.Error == null && e.Result.Results.GroupBy(f=> f.Address.FormattedAddress).Count() == 1) { var validated = new Address_Validated(e.Result.Results.First(), null); //MessageBus.Current.SendMessage(new Address_Validated(e.Result.Results.First(), search_Address)); tcs.TrySetResult(validated); } else { tcs.SetCanceled(); //MessageBus.Current.SendMessage(search_Address.To_Manual()); //var task = Manually_Validate_Address(textAddress); //task.Wait(); } }; geocoding.GeocodeAsync(new maps.GeocodeService.GeocodeRequest { Credentials = new Microsoft.Maps.MapControl.Credentials() { Token = maps.ServiceHelper.GeocodeServiceCredentials }, Culture = System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(), Query = textAddress }); return tcs.Task; }
public void SubscriptionWithCancelledTaskCanBeDisposed() { var sp = ServiceProviderHelper.CreateServiceProvider(); using (var bus = (MessageBus)sp.GetRequiredService<IMessageBus>()) { var subscriber = new TestSubscriber(new[] { "key" }); var wh = new ManualResetEventSlim(); IDisposable subscription = bus.Subscribe(subscriber, null, async (result, state) => { if (result.Terminal) { return false; } await Task.Delay(50); var tcs = new TaskCompletionSource<bool>(); tcs.SetCanceled(); wh.Set(); return await tcs.Task; }, 10, null); bus.Publish("me", "key", "hello"); wh.Wait(); subscription.Dispose(); } }
public async Task Should_invoke_on_message(TransportTransactionMode transactionMode) { var onMessageCalled = new TaskCompletionSource<MessageContext>(); OnTestTimeout(() => onMessageCalled.SetCanceled()); await StartPump(context => { var body = Encoding.UTF8.GetString(context.Body); Assert.AreEqual("", body, "Should pass the body"); onMessageCalled.SetResult(context); return Task.FromResult(0); }, context => Task.FromResult(ErrorHandleResult.Handled), transactionMode); await SendMessage(InputQueueName, new Dictionary<string, string> { {"MyHeader", "MyValue"} }); var messageContext = await onMessageCalled.Task; Assert.False(string.IsNullOrEmpty(messageContext.MessageId), "Should pass the native message id"); Assert.AreEqual("MyValue", messageContext.Headers["MyHeader"], "Should pass the message headers"); }
public Task<bool> CallVote(IEnumerable<IVoter> voters) { // Check if a vote is already in process if(_voteCompletionSource != null && !_voteCompletionSource.Task.IsCompleted) { // Create a task in a cancelled state then return it TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>(); taskCompletionSource.SetCanceled(); return taskCompletionSource.Task; } // Ensure the voters are enumerated only once, and convert nulls to empty lists List<IVoter> votersList = (voters ?? Enumerable.Empty<IVoter>()).ToList(); // Prepare the initial state for the vote _votesRemaining = votersList.Count; _yesVotes = _noVotes = 0; _voteCompletionSource = new TaskCompletionSource<bool>(); // Call RequestVote on each voter, and pass the results to CastVote foreach (IVoter voter in votersList) { voter.RequestVote().ContinueWith(CastVote); } // Return a task which can be controlled using _voteCompletionSource return _voteCompletionSource.Task; }
public static Task<bool> ConfirmationAsync(string title, string question) { var dataContext = new ConfirmModel { Title = title, Question = question }; var inputWindow = new ConfirmWindow { DataContext = dataContext }; var tcs = new TaskCompletionSource<bool>(); inputWindow.Closed += (sender, args) => { if (inputWindow.DialogResult != null) tcs.SetResult(inputWindow.DialogResult.Value); else tcs.SetCanceled(); }; inputWindow.Show(); return tcs.Task; }
public Task<Stream> GetStreamAsync(Uri uri, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<Stream>(); try { HttpWebRequest request = WebRequest.CreateHttp(uri); request.AllowReadStreamBuffering = true; request.BeginGetResponse(ar => { if (cancellationToken.IsCancellationRequested) { tcs.SetCanceled(); return; } try { Stream stream = request.EndGetResponse(ar).GetResponseStream(); tcs.TrySetResult(stream); } catch (Exception ex) { tcs.TrySetException(ex); } }, null); } catch (Exception ex) { tcs.TrySetException(ex); } return tcs.Task; }
public static Task<int> GetIntAsync(CancellationToken token = default(CancellationToken)) { var tcs = new TaskCompletionSource<int>(); if (token.IsCancellationRequested) { tcs.SetCanceled(); return tcs.Task; } var timer = new System.Timers.Timer(3000); timer.AutoReset = false; timer.Elapsed += (s, e) => { tcs.TrySetResult(10); timer.Dispose(); }; if (token.CanBeCanceled) { token.Register(() => { tcs.TrySetCanceled(); timer.Dispose(); }); } timer.Start(); return tcs.Task; }
private Task<ContentProviderResult> ExtractContent(ContentProviderHttpRequest request) { var validProviders = _contentProviders.Where(c => c.IsValidContent(request.RequestUri)) .ToList(); if (validProviders.Count == 0) { return TaskAsyncHelper.FromResult<ContentProviderResult>(null); } var tasks = validProviders.Select(c => c.GetContent(request)).ToArray(); var tcs = new TaskCompletionSource<ContentProviderResult>(); Task.Factory.ContinueWhenAll(tasks, completedTasks => { var faulted = completedTasks.FirstOrDefault(t => t.IsFaulted); if (faulted != null) { tcs.SetException(faulted.Exception); } else if (completedTasks.Any(t => t.IsCanceled)) { tcs.SetCanceled(); } else { ContentProviderResult result = completedTasks.Select(t => t.Result) .FirstOrDefault(content => content != null); tcs.SetResult(result); } }); return tcs.Task; }
public void Dispose() { _currentCompletionSource?.SetCanceled(); var removeInstanceCommand = $"{JsType}.removeInstance('{_instanceId}')"; WebAssemblyRuntime.InvokeJS(removeInstanceCommand); }
private static Task WriteResponse(OwinContext context, IDictionary<string, object> env) { var tcs = new TaskCompletionSource<int>(); var cancellationToken = (CancellationToken) env[OwinKeys.CallCancelled]; if (cancellationToken.IsCancellationRequested) { tcs.SetCanceled(); } else { try { env[OwinKeys.StatusCode] = context.Response.Status.Code; env[OwinKeys.ReasonPhrase] = context.Response.Status.Description; env[OwinKeys.ResponseHeaders] = context.Response.Headers; if (context.Response.WriteFunction != null) { return context.Response.WriteFunction((Stream) env[OwinKeys.ResponseBody]); } tcs.SetResult(0); } catch (Exception ex) { tcs.SetException(ex); } } return tcs.Task; }
public void TestEventAsyncPattern() { new Thread(() => { var webClient = new WebClient(); var source = new TaskCompletionSource<string>(); webClient.DownloadStringCompleted += (sender, args) => { if (args.Cancelled) { source.SetCanceled(); return; } if (args.Error != null) { source.SetException(args.Error); return; } source.SetResult(args.Result); }; webClient.DownloadStringAsync(new Uri(UrlToTest, UriKind.Absolute), null); source.Task.Wait(); var result = source.Task.Result; Assert.IsNotNull(result); this.EnqueueTestComplete(); }).Start(); }
public void Should_call_onBulkheadRejected_with_passed_context() { string executionKey = Guid.NewGuid().ToString(); Context contextPassedToExecute = new Context(executionKey); Context contextPassedToOnRejected = null; Func<Context, Task> onRejectedAsync = async ctx => { contextPassedToOnRejected = ctx; await TaskHelper.EmptyTask.ConfigureAwait(false); }; BulkheadPolicy<int> bulkhead = Policy.BulkheadAsync<int>(1, onRejectedAsync); TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); using (CancellationTokenSource cancellationSource = new CancellationTokenSource()) { Task.Run(() => { bulkhead.ExecuteAsync(async () => { await tcs.Task.ConfigureAwait(false); return 0; }); }); Within(shimTimeSpan, () => bulkhead.BulkheadAvailableCount.Should().Be(0)); // Time for the other thread to kick up and take the bulkhead. bulkhead.Awaiting(async b => await b.ExecuteAsync(() => Task.FromResult(1), contextPassedToExecute)).ShouldThrow<BulkheadRejectedException>(); cancellationSource.Cancel(); tcs.SetCanceled(); } contextPassedToOnRejected.Should().NotBeNull(); contextPassedToOnRejected.ExecutionKey.Should().Be(executionKey); contextPassedToOnRejected.Should().BeSameAs(contextPassedToExecute); }
public static Task<int> StartProcess (ProcessStartInfo psi, TextWriter stdout, TextWriter stderr, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<int> (); if (cancellationToken.CanBeCanceled && cancellationToken.IsCancellationRequested) { tcs.SetCanceled (); return tcs.Task; } psi.UseShellExecute = false; if (stdout != null) { psi.RedirectStandardOutput = true; } if (stderr != null) { psi.RedirectStandardError = true; } var p = Process.Start (psi); if (cancellationToken.CanBeCanceled) cancellationToken.Register (() => { try { if (!p.HasExited) { p.Kill (); } } catch (InvalidOperationException ex) { if (ex.Message.IndexOf ("already exited") < 0) throw; } }); p.EnableRaisingEvents = true; if (psi.RedirectStandardOutput) { bool stdOutInitialized = false; p.OutputDataReceived += (sender, e) => { try { if (stdOutInitialized) stdout.WriteLine (); stdout.Write (e.Data); stdOutInitialized = true; } catch (Exception ex) { tcs.SetException (ex); } }; p.BeginOutputReadLine (); } if (psi.RedirectStandardError) { bool stdErrInitialized = false; p.ErrorDataReceived += (sender, e) => { try { if (stdErrInitialized) stderr.WriteLine (); stderr.Write (e.Data); stdErrInitialized = true; } catch (Exception ex) { tcs.SetException (ex); } }; p.BeginErrorReadLine (); } p.Exited += (sender, e) => tcs.SetResult (p.ExitCode); return tcs.Task; }
public async Task Should_reset_delivery_counter(TransportTransactionMode transactionMode) { var onErrorInvoked = new TaskCompletionSource<ErrorContext>(); OnTestTimeout(() => onErrorInvoked.SetCanceled()); var numberOfOnErrorInvocations = 0; await StartPump( context => { throw new Exception("Simulated exception"); }, async context => { numberOfOnErrorInvocations += 1; if (numberOfOnErrorInvocations == 1) { await SendMessage(InputQueueName, context.Message.Headers, context.TransportTransaction); } else { onErrorInvoked.SetResult(context); } return ErrorHandleResult.Handled; }, transactionMode); await SendMessage(InputQueueName, new Dictionary<string, string> { { "MyHeader", "MyValue" } }); var errorContext = await onErrorInvoked.Task; Assert.AreEqual(1, errorContext.ImmediateProcessingFailures, "Should track delivery attempts between immediate retries"); }
/// <summary> /// Executes the action on the UI thread asynchronously. /// </summary> /// <param name = "action">The action to execute.</param> public Task OnUIThreadAsync(Action action) { var completionSource = new TaskCompletionSource<bool>(); UIApplication.SharedApplication.InvokeOnMainThread(() => { try { action(); completionSource.SetResult(true); } catch (TaskCanceledException) { completionSource.SetCanceled(); } catch (Exception ex) { completionSource.SetException(ex); } }); return completionSource.Task; }
Task<ALAsset> GetAsset (AssetDescription description, CancellationToken token) { var tcs = new TaskCompletionSource<ALAsset> (); Task.Factory.StartNew (() => { if (token.IsCancellationRequested) { tcs.SetCanceled (); return; } _library.Value.AssetForUrl (new NSUrl (description.AssetUrl), (asset) => { if (asset == null) { tcs.SetException (new Exception ("No asset found for url")); return; } if (asset.DefaultRepresentation == null) { tcs.SetException (new Exception ("No representation found for the asset")); return; } tcs.SetResult (asset); }, error => { tcs.SetException (new Exception (error.ToString ())); }); }, token).RouteExceptions (tcs); return tcs.Task; }
public static Task<string> QuestionAsync(string title, string question) { var dataContext = new InputModel { Title = title, Question = question }; var inputWindow = new InputWindow { DataContext = dataContext }; var tcs = new TaskCompletionSource<string>(); inputWindow.Closed += (sender, args) => { if (inputWindow.DialogResult == true) tcs.SetResult(dataContext.Answer); else tcs.SetCanceled(); }; inputWindow.Show(); return tcs.Task; }
/// <summary> /// Static constructor. /// </summary> static WebClientExtension() { var taskCompletionSource = new TaskCompletionSource<byte[]>(); taskCompletionSource.SetCanceled(); WebClientExtension.PreCancelledTask = taskCompletionSource.Task; }
public override void DidAuthorizePayment(PKPaymentAuthorizationViewController controller, PKPayment payment, Action <PKPaymentAuthorizationStatus> completion) { var applePayClient = new BTApplePayClient(braintreeClient); applePayClient.TokenizeApplePayPayment(payment, (tokenizedApplePayPayment, error) => { if (error == null) { if (string.IsNullOrEmpty(tokenizedApplePayPayment.Nonce)) { payTcs?.SetCanceled(); } else { OnTokenizationSuccessful?.Invoke(this, tokenizedApplePayPayment.Nonce); payTcs?.TrySetResult(tokenizedApplePayPayment.Nonce); } completion(PKPaymentAuthorizationStatus.Success); } else { OnTokenizationError?.Invoke(this, "Error - Payment tokenization failed"); payTcs?.TrySetException(new Exception("Error - Payment tokenization failed")); completion(PKPaymentAuthorizationStatus.Failure); } }); }
/// <summary> /// If AutoSaveChanges is set this method will auto commit changes /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> protected virtual Task<int> SaveChanges(CancellationToken cancellationToken) { var source = new TaskCompletionSource<int>(); if (AutoSaveChanges) { var registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { if (cancellationToken.IsCancellationRequested) { source.SetCanceled(); return source.Task; } registration = cancellationToken.Register(CancelIgnoreFailure); } try { return _uow.SaveChangesAsync(cancellationToken); } catch (Exception e) { source.SetException(e); } finally { registration.Dispose(); } } return source.Task; }
private void OnDestroy() { kill = true; OnMoveFinish = null; OnGiveUp = null; roomJoiningPromise?.SetCanceled(); }
public void EndListening() { IsListening = false; lock (_guard) { _waitingTasks.Clear(); _finalTaskCompletionSource?.SetCanceled(); _finalTaskCompletionSource = null; } }
public async Task Start(CancellationToken cancellationToken) { cancellationToken.Register(() => { lock (_feedStateManipulation) { isCanceled = true; _dormantStateTask?.SetCanceled(); } }); UpdateState(Feed.CurrentState); while (true) { if (cancellationToken.IsCancellationRequested) { break; } SyncFeedState currentStateLocal; TaskCompletionSource <object?>?dormantTaskLocal; lock (_feedStateManipulation) { currentStateLocal = _currentFeedState; dormantTaskLocal = _dormantStateTask; if (isCanceled) { break; } } if (currentStateLocal == SyncFeedState.Dormant) { if (Logger.IsDebug) { Logger.Debug($"{GetType().Name} is going to sleep."); } if (dormantTaskLocal == null) { if (Logger.IsWarn) { Logger.Warn("Dormant task is NULL when trying to await it"); } } await(dormantTaskLocal?.Task ?? Task.CompletedTask); if (Logger.IsDebug) { Logger.Debug($"{GetType().Name} got activated."); } } else if (currentStateLocal == SyncFeedState.Active) { T request = await(Feed.PrepareRequest() ?? Task.FromResult <T>(default !)); // just to avoid null refs
public void FinishReceiveData(bool success) { _webSocketReceiving = 0; if (!success) { _webSocketReceiveState = WebSocketReceiveState.Close; _webSocketReceiveTcs?.SetCanceled(); _webSocketTcsReceivedClose?.TrySetResult(null); return; } ParseWebSocketReceivedData(); }
internal void Cancel() { if (_requestTask?.Task.IsCompleted == false) { _requestTask?.SetCanceled(); if (_requestID != null) { var err = Interop.CancelRequest(_service.handle, (int)_requestID); err.ThrowIfFailed($"Unable to cancel service request, Type: {_type}, ID: {_requestID}"); } errorCode = Interop.ErrorCode.Canceled; } }
private void InternalExecuteAsync(AseCommand command, AseTransaction transaction, TaskCompletionSource <int> rowsAffectedSource = null, TaskCompletionSource <DbDataReader> readerSource = null, CommandBehavior behavior = CommandBehavior.Default) { AssertExecutionStart(); try { SendPacket(new NormalPacket(BuildCommandTokens(command, behavior))); var doneHandler = new DoneTokenHandler(); var messageHandler = new MessageTokenHandler(EventNotifier); var dataReaderHandler = readerSource != null ? new DataReaderTokenHandler() : null; ReceiveTokens( new EnvChangeTokenHandler(_environment), messageHandler, dataReaderHandler, new ResponseParameterTokenHandler(command.AseParameters), doneHandler); AssertExecutionCompletion(doneHandler); if (transaction != null && doneHandler.TransactionState == TranState.TDS_TRAN_ABORT) { transaction.MarkAborted(); } messageHandler.AssertNoErrors(); if (doneHandler.Canceled) { rowsAffectedSource?.SetCanceled(); readerSource?.SetCanceled(); } else { rowsAffectedSource?.SetResult(doneHandler.RowsAffected); readerSource?.SetResult(new AseDataReader(dataReaderHandler.Results(), command, behavior)); } } catch (Exception ex) { rowsAffectedSource?.SetException(ex); readerSource?.SetException(ex); } }
private void Dispose(bool disposing) { if (_disposed) { return; } if (Logging.IsEnabled) { Logging.Info(this, disposing, $"{nameof(Dispose)}"); } if (disposing) { TaskCompletionSource?.SetCanceled(); } _disposed = true; }
public void Stop() { if (_completationConfirm.Task.Status == TaskStatus.Running) { _completationConfirm?.SetCanceled(); } _completationConfirm = null; if (_cts == null) { throw new InvalidOperationException(); } if (State != NetworkServiceState.Stoped) { State = NetworkServiceState.Stoped; _cts.Cancel(); _cts = null; } }
public async Task TestCancellation() { var store = new Mock <ICheckpointStore>(); store.Setup(d => d.GetCheckpointDataAsync(It.IsAny <string>(), It.IsAny <CancellationToken>())).ReturnsAsync(new CheckpointData(10)); using (var cts = new CancellationTokenSource()) using (ICheckpointer checkpointer1 = await Checkpointer.CreateAsync("id1", store.Object)) { var tcs = new TaskCompletionSource <bool>(); cts.Token.Register(() => tcs.SetCanceled()); store.Setup(d => d.SetCheckpointDataAsync(It.IsAny <string>(), It.IsAny <CheckpointData>(), It.IsAny <CancellationToken>())).Returns(tcs.Task); Task result = checkpointer1.CommitAsync(new[] { MessageWithOffset(20) }, new IMessage[] { }, Option.None <DateTime>(), Option.None <DateTime>(), CancellationToken.None); cts.Cancel(); await Assert.ThrowsAsync <TaskCanceledException>(() => result); Assert.Equal(20, checkpointer1.Offset); await checkpointer1.CloseAsync(CancellationToken.None); } }
public static Task <int> WaitForExitAsync(this Process self, CancellationToken cancellationToken) { if (self == null) { throw new ArgumentNullException(nameof(self)); } var tcs = new TaskCompletionSource <int>(); self.Exited += (sender, args) => { if (!cancellationToken.IsCancellationRequested) { tcs.SetResult(self.ExitCode); } }; self.EnableRaisingEvents = true; cancellationToken.Register(() => { try { Debug.WriteLine("Kill Start"); self.Kill(); } catch (SystemException ex) when(ex is Win32Exception || ex is NotSupportedException || ex is InvalidOperationException) { Debug.WriteLine($"Process Kill Exception : {ex.Message}"); } Debug.WriteLine("SetCanceled Start"); tcs.SetCanceled(); }); return(tcs.Task); }
public void TaskToObservable_NonVoid_Canceled_BeforeDispose() { var taskScheduler = new TestTaskScheduler(); var taskFactory = new TaskFactory(taskScheduler); var res = default(ITestableObserver <int>); taskFactory.StartNew(() => { var scheduler = new TestScheduler(); var taskSource = new TaskCompletionSource <int>(); taskSource.Task.ContinueWith(t => { var e = t.Exception; }); scheduler.ScheduleAbsolute(300, () => taskSource.SetCanceled()); res = scheduler.Start(() => taskSource.Task.ToObservable() ); }); res.Messages.AssertEqual( OnError <int>(300, ex => ex is TaskCanceledException) ); }
/// <summary> /// Flattens exception structure of AggregateExceptions without the need of catching/rethrowing /// </summary> public static Task <T> FlattenExceptions <T>(this Task <T> task) { if (task == null) { throw new ArgumentNullException("task"); } return(task.ContinueWith(previousTask => { var tcs = new TaskCompletionSource <T>(); switch (previousTask.Status) { case TaskStatus.Faulted: // Exceptions occured in (one of the) previous tasks if (previousTask.Exception == null) { throw new InvalidOperationException("Faulted Task should have Exception"); } tcs.SetException(previousTask.Exception.Flatten().InnerExceptions); break; case TaskStatus.Canceled: tcs.SetCanceled(); break; case TaskStatus.RanToCompletion: tcs.SetResult(previousTask.Result); break; default: throw new InvalidOperationException($"Invalid task status: {previousTask.Status}"); } return tcs.Task; }).Unwrap()); }
/// <summary> /// Executes the action on the UI thread asynchronously. /// </summary> /// <param name = "action">The action to execute.</param> public virtual Task OnUIThreadAsync(Func <Task> action) { var completionSource = new TaskCompletionSource <bool>(); UIApplication.SharedApplication.InvokeOnMainThread(async() => { try { await action(); completionSource.SetResult(true); } catch (TaskCanceledException) { completionSource.SetCanceled(); } catch (Exception ex) { completionSource.SetException(ex); } }); return(completionSource.Task); }
public static Task <TResult> Then <TResult>(this Task task, Func <Task, TResult> continuationFunction, CancellationToken token) { return(task .ContinueWith(t => { var tcs = new TaskCompletionSource <TResult>(); if (t.IsCanceled) { tcs.SetCanceled(); } else if (t.Exception != null) // t.IsFaulted is true { tcs.SetException(t.Exception.GetBaseException()); } else { tcs.SetResult(continuationFunction(t)); } return tcs.Task; }, token, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current) .Unwrap()); }
static Task <TResult> InternalExecuteAsync <TResult>(IResult result, CoroutineExecutionContext context) { var taskSource = new TaskCompletionSource <TResult>(); EventHandler <ResultCompletionEventArgs> completed = null; completed = (s, e) => { result.Completed -= completed; if (e.Error != null) { taskSource.SetException(e.Error); } else if (e.WasCancelled) { taskSource.SetCanceled(); } else { var rr = result as IResult <TResult>; taskSource.SetResult(rr != null ? rr.Result : default(TResult)); } }; try { IoC.BuildUp(result); result.Completed += completed; result.Execute(context ?? new CoroutineExecutionContext()); } catch (Exception ex) { result.Completed -= completed; taskSource.SetException(ex); } return(taskSource.Task); }
private static Task <T> ExecuteOnNewSTAThread <T>(TaskCompletionSource <T> taskCompletionSource, Action <TaskCompletionSource <T> > action, CancellationToken cancellationToken) { var thread = new Thread(() => { try { cancellationToken.ThrowIfCancellationRequested(); action(taskCompletionSource); } catch (OperationCanceledException) { taskCompletionSource.SetCanceled(); } catch (Exception e) { taskCompletionSource.SetException(e); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); return(taskCompletionSource.Task); }
/** * This combinator emulates the behaviour of thenCombine operation on Java CompletableFuture */ public static Task <V> ThenCombine <T, U, V>(this Task <T> task1, Task <U> task2, Func <T, U, V> combiner) { TaskCompletionSource <V> promise = new TaskCompletionSource <V>(); task1.ContinueWith(t1 => { task2.ContinueWith(t2 => { if (t1.Status == TaskStatus.Canceled || t2.Status == TaskStatus.Canceled) { promise.SetCanceled(); } else if (t1.Exception != null || t2.Exception != null) { // termination promise exceptionally var elist = new List <Exception>(); if (t1.Exception != null) { elist.Add(t1.Exception); } if (t2.Exception != null) { elist.Add(t2.Exception); } AggregateException exc = new AggregateException(elist); promise.SetException(exc); } else { promise.SetResult(combiner(t1.Result, t2.Result)); } }, TaskContinuationOptions.ExecuteSynchronously); }, TaskContinuationOptions.ExecuteSynchronously); return(promise.Task); }
void Process() { while (!disposed) { waitEvent.WaitOne(); try { currentWork.Invoke(Target); currentWorkTask.SetResult(Target); } catch (Exception ex) { currentWorkTask.SetException(ex); } currentWork = null; currentWorkTask = null; waitEvent.Reset(); } currentWorkTask?.SetCanceled(); }
/// <summary> /// Sends this <see cref="ISnmpMessage"/> and handles the response from agent. /// </summary> /// <param name="request">The <see cref="ISnmpMessage"/>.</param> /// <param name="receiver">Port number.</param> /// <returns></returns> public static async Task <ISnmpMessage> GetResponseAsync(this ISnmpMessage request, IPEndPoint receiver, CancellationToken cancellationToken = default(CancellationToken)) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (receiver == null) { throw new ArgumentNullException(nameof(receiver)); } var code = request.TypeCode(); if (code == SnmpType.TrapV1Pdu || code == SnmpType.TrapV2Pdu || code == SnmpType.ReportPdu) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", code)); } var tcs = new TaskCompletionSource <bool>(); using (var cancel = cancellationToken.Register(() => tcs.SetCanceled())) using (var socket = receiver.GetSocket()) { var response = request.GetResponseAsync(receiver, socket); var result = await Task.WhenAny(tcs.Task, response).ConfigureAwait(false); if (result == tcs.Task) { // This should always be true.... // Otherwise throw your own. cancellationToken.ThrowIfCancellationRequested(); } return(await response.ConfigureAwait(false)); } }
public void TestInvalidSetCanceled() { this.TestWithError(() => { var tcs = new TaskCompletionSource(); tcs.SetResult(); Exception exception = null; try { tcs.SetCanceled(); } catch (Exception ex) when(!(ex is ThreadInterruptedException)) { exception = ex; } Specification.Assert(exception is InvalidOperationException, "Threw unexpected exception {0}.", exception.GetType()); Specification.Assert(false, "Reached test assertion."); }, expectedError: "Reached test assertion.", replay: true); }
/// <summary> /// Stops ongoing WPS provisioning /// </summary> /// <since_tizen> 5 </since_tizen> /// <feature>http://tizen.org/feature/network.wifi</feature> /// <privilege>http://tizen.org/privilege/network.set</privilege> /// <privilege>http://tizen.org/privilege/network.get</privilege> /// <exception cref="NotSupportedException">Thrown when the Wi-Fi is not supported.</exception> /// <exception cref="UnauthorizedAccessException">Thrown when permission is denied.</exception> /// <exception cref="OutOfMemoryException">Thrown when the system is out of memory.</exception> /// <exception cref="InvalidOperationException">Thrown when the method failed due to an invalid operation.</exception> public static void CancelWps() { Log.Debug(Globals.LogTag, "CancelWps"); int ret = Interop.WiFi.CancelWps(WiFiManagerImpl.Instance.GetSafeHandle()); if (ret != (int)WiFiError.None) { Log.Error(Globals.LogTag, "Failed to cancel Wps, Error - " + (WiFiError)ret); WiFiErrorFactory.ThrowWiFiException(ret, WiFiManagerImpl.Instance.GetSafeHandle().DangerousGetHandle()); } // Cancel awaiting tasks if (wpsWithoutSsidTask != null) { Log.Info(Globals.LogTag, "Cancel ConnectWpsWithoutSsidAsync()"); wpsWithoutSsidTask.SetCanceled(); } foreach (var item in _wpsTaskMap) { Log.Info(Globals.LogTag, "Cancel ConnectWpsAsync() by " + item.Key.GetHashCode()); item.Value.SetCanceled(); } _wpsTaskMap.Clear(); }
public Task ScheduleWithCancellation(Action command, long delay, TimeUnit unit, CancellationToken token) { var tcs = new TaskCompletionSource <object>(); var continueTask = tcs.Task.ContinueWith(t => { if (!t.IsCanceled) { command(); } }, token); new Timer(o => { if (token.IsCancellationRequested) { tcs.SetCanceled(); } else { tcs.SetResult(null); } }, null, unit.ToMillis(delay), Timeout.Infinite); return(continueTask); }
public async void WhenAllCompleted() { var t1 = Task.FromResult(1); var tcs2 = new TaskCompletionSource <int>(); tcs2.SetException(new Exception()); var t2 = tcs2.Task; var tcs3 = new TaskCompletionSource <int>(); tcs3.SetCanceled(); var t3 = tcs3.Task; var result = await new[] { t1, t2, t3 }.WhenAllCompleted(); Assert.Equal(t1, result[0]); // Returns in same order Assert.Equal(t2, result[1]); Assert.Equal(t3, result[2]); Assert.Equal(TaskStatus.RanToCompletion, t1.Status); Assert.Equal(TaskStatus.Faulted, t2.Status); Assert.Equal(TaskStatus.Canceled, t3.Status); }
public Task <string> SendAsync(string uri, string method, IDictionary <string, string> headers, string jsonContent, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource <string>(); UnityCoroutineHelper.StartCoroutine(() => SendAsync(uri, method, headers, jsonContent, request => { if (cancellationToken.IsCancellationRequested) { tcs.SetCanceled(); return; } if (request.isNetworkError) { tcs.SetException(new NetworkIngestionException()); } else if (request.isHttpError) { tcs.SetException(new HttpIngestionException($"Operation returned an invalid status code '{request.responseCode}'") { Method = request.method, RequestUri = new Uri(request.url), StatusCode = (int)request.responseCode, RequestContent = jsonContent, ResponseContent = request.downloadHandler.text }); } else { var responseContent = request.downloadHandler.text; AppCenterLog.Verbose(AppCenterLog.LogTag, $"HTTP response status={(int)request.responseCode} payload={responseContent}"); tcs.SetResult(responseContent); } })); return(tcs.Task); }
/// <inheritdoc /> public override async Task <bool> Connect(CancellationToken cancellationToken) { if (Connected) { return(true); } try { await client.LoginAsync(TokenType.Bot, botToken, true).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); await client.StartAsync().ConfigureAwait(false); var channelsAvailable = new TaskCompletionSource <object>(); client.Ready += () => { channelsAvailable.TrySetResult(null); return(Task.CompletedTask); }; using (cancellationToken.Register(() => channelsAvailable.SetCanceled())) await channelsAvailable.Task.ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (Exception e) { logger.LogWarning("Error connecting to Discord: {0}", e); return(false); } return(true); }
public void CancelledTaskHandledWhenStartingLongPolling() { var tcs = new TaskCompletionSource <IResponse>(); tcs.SetCanceled(); var httpClient = new Mock <IHttpClient>(); httpClient.Setup(c => c.Post(It.IsAny <string>(), It.IsAny <Action <IRequest> >(), It.IsAny <IDictionary <string, string> >(), It.IsAny <bool>())) .Returns(tcs.Task); var mockConnection = new Mock <IConnection>(); mockConnection.Setup(c => c.TotalTransportConnectTimeout).Returns(TimeSpan.FromSeconds(15)); var longPollingTransport = new LongPollingTransport(httpClient.Object); var unwrappedException = Assert.Throws <AggregateException>(() => longPollingTransport.Start(mockConnection.Object, null, CancellationToken.None) .Wait(TimeSpan.FromSeconds(5))).InnerException; Assert.IsType <OperationCanceledException>(unwrappedException); }