public static void CancelBeforeWait()
        {
            CountdownEvent countdownEvent = new CountdownEvent(2);
            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);
            string message = "CancelBeforeWait:  > Cancellation token does not match.";
            EnsureOperationCanceledExceptionThrown(() => countdownEvent.Wait(ct), ct, message);
            EnsureOperationCanceledExceptionThrown(() => countdownEvent.Wait(millisec, ct), ct, message);
            EnsureOperationCanceledExceptionThrown(() => countdownEvent.Wait(timeSpan, ct), ct, message);

            countdownEvent.Dispose();
        }
        public static void CancelAfterWait()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0); // semaphore that will block all waiters

            Task.Run(
                () =>
                {
                    for (int i = 0; i < 300; i++) ;
                    cancellationTokenSource.Cancel();
                });

            //Now wait.. the wait should abort and an exception should be thrown
            EnsureOperationCanceledExceptionThrown(
               () => semaphoreSlim.Wait(cancellationToken),
               cancellationToken, "CancelAfterWait:  An OCE(null) should have been thrown that references the cancellationToken.");

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually
        }
    /// <summary>
    /// Creates an instance of the test class for the given test case. Sends the <see cref="ITestClassConstructionStarting"/>
    /// and <see cref="ITestClassConstructionFinished"/> messages as appropriate.
    /// </summary>
    /// <param name="testCase">The test case</param>
    /// <param name="testClassType">The type of the test class</param>
    /// <param name="constructorArguments">The constructor arguments for the test class</param>
    /// <param name="displayName">The display name of the test case</param>
    /// <param name="messageBus">The message bus used to send the test messages</param>
    /// <param name="timer">The timer used to measure the time taken for construction</param>
    /// <param name="cancellationTokenSource">The cancellation token source</param>
    /// <returns></returns>
    public static object CreateTestClass(this ITestCase testCase,
                                         Type testClassType,
                                         object[] constructorArguments,
                                         string displayName,
                                         IMessageBus messageBus,
                                         ExecutionTimer timer,
                                         CancellationTokenSource cancellationTokenSource)
    {
        object testClass = null;

        if (!messageBus.QueueMessage(new TestClassConstructionStarting(testCase, displayName)))
            cancellationTokenSource.Cancel();

        try
        {
            if (!cancellationTokenSource.IsCancellationRequested)
                timer.Aggregate(() => testClass = Activator.CreateInstance(testClassType, constructorArguments));
        }
        finally
        {
            if (!messageBus.QueueMessage(new TestClassConstructionFinished(testCase, displayName)))
                cancellationTokenSource.Cancel();
        }

        return testClass;
    }
Beispiel #4
0
        /// <summary>Requests the execution of the action delegate.</summary>
        public void InvokeAccumulated()
        {
            CancellationToken?token = null;

            lock (cancellationTokenSourceLock)
            {
                if (mode == ThrottledActionMode.InvokeOnlyIfIdleForDelayTime || cancellationTokenSource == null)
                {
                    cancellationTokenSource?.Cancel();
                    cancellationTokenSource = new CancellationTokenSource();
                    token = cancellationTokenSource.Token;
                }
            }

            if (token != null)
            {
                Task.Delay(delayTime, token.Value).ContinueWith(t =>
                {
                    lock (cancellationTokenSourceLock)
                    {
                        cancellationTokenSource = null;
                    }
                    TaskHelper.Run(action, taskScheduler);
                }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
            }
        }
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            // Stop called without start
            if (_executingThread is null)
            {
                return;
            }

            _logger.LogInformation($"{DateTime.Now} Digitalstrom Event Subscriber Service is stopping.");

            _dssEventSubscriber?.Dispose();
            _dssEventSubscriber = null;

            _persistenceQueue?.CompleteAdding();
            _persistenceQueue = null;

            try
            {
                // Signal cancellation to the executing method
                _cancellationSource?.Cancel();
            }
            finally
            {
                // Wait until the thread completes or the stop token triggers
                await Task.WhenAny(_executingThread, Task.Delay(Timeout.Infinite, cancellationToken));
            }
        }
        public override Task OnDeactivateAsync()
        {
            isStopping = true;

            currentTaskToken?.Cancel();

            return(base.OnDeactivateAsync());
        }
Beispiel #7
0
        private void StartFiring()
        {
            EverythingIsWellToFire();

            _fireCancelTokenSrc?.Cancel();
            _fireCancelTokenSrc = new CancellationTokenSource();
            var cancelToken = _fireCancelTokenSrc.Token;

            Timer.SpawnRepeating(_firingDelay, Fire, cancelToken);
        }
        public async Task Start()
        {
            if (AuthorizationManager.Token == null)
            {
                return;
            }

            switch (status)
            {
            case Status.Starting:
                startingTokenSource?.Cancel();
                break;

            case Status.Started:
                return;

            case Status.Stopped:
                break;

            case Status.Stopping:
                stoppingTokenSource?.Cancel();
                return;
            }

            try
            {
                Logger.Info("Long polling start requested");

                startingTokenSource = new CancellationTokenSource();
                var token = startingTokenSource.Token;
                status = Status.Starting;
                await Task.Delay(LongPoolingStartInterval, token);
            }
            catch
            {
                return;
            }

            try
            {
                Logger.Info("Long polling started");

                startedTokenSource?.Cancel();
                startedTokenSource = new CancellationTokenSource();
                var token = startedTokenSource.Token;
                status = Status.Started;
                await MainLoop(token);
            }
            catch
            {
                // ignored
            }

            Logger.Info("Long polling stopped");
        }
 private void ScheduleCancellation(TimeSpan timeout)
 {
     _ambientTimer = new AmbientEventTimer(timeout);
     System.Timers.ElapsedEventHandler?handler = null;
     handler = (source, e) =>
     {
         _ambientTimer.Elapsed -= handler;
         _tokenSource?.Cancel();
         _ambientTimer.Dispose();
     };
     _ambientTimer.Elapsed += handler;   // note that the handler will keep the timer and the token source alive until the event is raised, but the event is only raised once anyway, and there is no need to unsubscribe because the owner of the event is disposed when the event is triggered anyway
     _ambientTimer.Enabled  = true;
 }
Beispiel #10
0
        /// <summary>
        /// Replaces the existing addresses used with this <see cref="Subchannel"/>.
        /// <para>
        /// If the subchannel has an active connection and the new addresses contain the connected address
        /// then the connection is reused. Otherwise the subchannel will reconnect.
        /// </para>
        /// </summary>
        /// <param name="addresses"></param>
        public void UpdateAddresses(IReadOnlyList <BalancerAddress> addresses)
        {
            var requireReconnect = false;

            lock (Lock)
            {
                if (_addresses.SequenceEqual(addresses, BalancerAddressEqualityComparer.Instance))
                {
                    // Don't do anything if new addresses match existing addresses.
                    return;
                }

                _addresses.Clear();
                _addresses.AddRange(addresses);

                switch (_state)
                {
                case ConnectivityState.Idle:
                    break;

                case ConnectivityState.Connecting:
                case ConnectivityState.TransientFailure:
                    SubchannelLog.AddressesUpdatedWhileConnecting(_logger, Id);
                    requireReconnect = true;
                    break;

                case ConnectivityState.Ready:
                    // Transport uses the subchannel lock but take copy in an abundance of caution.
                    var currentAddress = CurrentAddress;
                    if (currentAddress != null && !_addresses.Contains(currentAddress))
                    {
                        requireReconnect = true;
                        SubchannelLog.ConnectedAddressNotInUpdatedAddresses(_logger, Id, currentAddress);
                    }
                    break;

                case ConnectivityState.Shutdown:
                    throw new InvalidOperationException($"Subchannel id '{Id}' has been shutdown.");

                default:
                    throw new ArgumentOutOfRangeException("state", _state, "Unexpected state.");
                }
            }

            if (requireReconnect)
            {
                _connectCts?.Cancel();
                Transport.Disconnect();
                RequestConnection();
            }
        }
Beispiel #11
0
 private async void HandleStartBuild(object sender, BuildEventArgs args)
 {
     try
     {
         startCancellationTokenSource?.Cancel();
         endCancellationTokenSource?.Cancel();
         startCancellationTokenSource = new CancellationTokenSource();
         cummulativeBuildSuccess      = true;
         await deviceList.SetColorAsync(0, 0, 255, startCancellationTokenSource.Token);
     }
     catch (Exception ex)
     {
         LoggingService.LogError("Failed to handle start build", ex);
     }
 }
Beispiel #12
0
        public void TestCancel()
        {
            using (var waitHandle = new ManualResetEvent(false))
            {
                // Monitor for a cancellation exception
                var task = new WaitTask("Test task", waitHandle);
                bool exceptionThrown = false;
                var cancellationTokenSource = new CancellationTokenSource();
                var waitThread = new Thread(() =>
                {
                    try
                    {
                        task.Run(cancellationTokenSource.Token);
                    }
                    catch (OperationCanceledException)
                    {
                        exceptionThrown = true;
                    }
                });

                // Start and then cancel the download
                waitThread.Start();
                Thread.Sleep(100);
                cancellationTokenSource.Cancel();
                waitThread.Join();

                exceptionThrown.Should().BeTrue(because: task.State.ToString());
            }
        }
Beispiel #13
0
        private void OnMouseEnteredStack(object?sender, StackContextElement e)
        {
            var realGlobalPosition = e.GlobalPosition;

            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource = new();

            Timer.Spawn(e.HoverDelay, () =>
            {
                _verbSystem.CloseGroupMenu();

                if (_contextMenuView.Menus.Count == 0)
                {
                    return;
                }

                OnCloseChildMenu(sender, e.ParentMenu?.Depth ?? 0);

                var filteredEntities = e.ContextEntities.Where(entity => !entity.Deleted);
                if (filteredEntities.Any())
                {
                    _contextMenuView.AddChildMenu(filteredEntities, realGlobalPosition, e);
                }
            }, _cancellationTokenSource.Token);
        }
Beispiel #14
0
        public async Task StopAsync(CancellationToken cancellationToken = default)
        {
            if (_cts is null)
            {
                throw new InvalidOperationException("Channel not yet started.");
            }

            _cts?.Cancel();

            if (_sendTask is not null)
            {
                try
                {
                    await _sendTask;
                }
                catch (OperationCanceledException)
                {
                }
            }

            await _stream.StopAsync();

            _cts?.Dispose();
            _cts = null;
        }
Beispiel #15
0
        private void OnAsynchronousRequestCancelled(object?state)
        {
            var request = (Request)state !;
            CancellationTokenSource?cancellationTokenSource = null;

            using (TakeLock(CancellationToken.None))
            {
                // Now try to remove it. It's possible that requests may already be null. You could
                // imagine that cancellation was requested, but before we could acquire the lock
                // here the computation completed and the entire CompleteWithTask synchronized
                // block ran. In that case, the requests collection may already be null, or it
                // (even scarier!) may have been replaced with another collection because another
                // computation has started.
                if (_requests != null)
                {
                    if (_requests.Remove(request))
                    {
                        if (_requests.Count == 0)
                        {
                            _requests = null;

                            if (_asynchronousComputationCancellationSource != null)
                            {
                                cancellationTokenSource = _asynchronousComputationCancellationSource;
                                _asynchronousComputationCancellationSource = null;
                                _computationActive = false;
                            }
                        }
                    }
                }
            }

            request.Cancel();
            cancellationTokenSource?.Cancel();
        }
Beispiel #16
0
        public void SetToIdle()
        {
            if (State == WorkState.Idle)
            {
                return;
            }
            Logger.Log("Setting database worker to Idle");

            switch (State)
            {
            case WorkState.CleanSearching:
                break;

            case WorkState.Populating:
                m_currentTaskCancellation?.Cancel();
                m_currentTaskCancellation = null;

                m_populateTask = m_populateSearchTask = null;
                break;

            case WorkState.Cleaning:
                break;
            }

            State = WorkState.Idle;

            m_onSetToIdleCallback?.Invoke();
            m_onSetToIdleCallback = null;
        }
Beispiel #17
0
        /// <summary>
        /// Starts receiving <see cref="Update"/>s on the ThreadPool
        /// </summary>
        /// <param name="allowedUpdates">Indicates which <see cref="UpdateType"/>s are allowed to be received. null means all updates</param>
        /// <param name="errorHandler">The function used to handle <see cref="Exception"/>s</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> with which you can stop receiving</param>
        public void StartReceiving(
            UpdateType[]?allowedUpdates = default,
            Func <Exception, CancellationToken, Task>?errorHandler = default,
            CancellationToken cancellationToken = default)
        {
            lock (_lock)
            {
                if (IsReceiving)
                {
                    throw new InvalidOperationException("Receiving is already in progress");
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                IsReceiving = true;

                _cancellationTokenSource = new CancellationTokenSource();
                cancellationToken.Register(() => _cancellationTokenSource?.Cancel());
                cancellationToken = _cancellationTokenSource.Token;
            }

            StartReceivingInternal(allowedUpdates, errorHandler, cancellationToken);
        }
Beispiel #18
0
        public override void Stop()
        {
            base.Stop();

            _cts?.Cancel();
            Radius = 0;
        }
Beispiel #19
0
        /// <summary>
        /// Changes to a specific <see cref="CustomPlatform"/>
        /// </summary>
        /// <param name="platform">The <see cref="CustomPlatform"/> to change to</param>
        public async Task ChangeToPlatformAsync(CustomPlatform platform)
        {
            if (platform == _platformManager.ActivePlatform)
            {
                return;
            }
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();
            _cancellationTokenSource = new CancellationTokenSource();
            CancellationToken token = _cancellationTokenSource.Token;

            DestroyPlatform(_platformManager.ActivePlatform.gameObject);
            if (platform == _platformManager.RandomPlatform)
            {
                platform = RandomPlatform;
            }
            _platformManager.ActivePlatform = platform;
            if (platform.isDescriptor)
            {
                platform = await ReplaceDescriptorAsync(platform);
            }
            if (token.IsCancellationRequested)
            {
                return;
            }
            _platformManager.ActivePlatform = platform;
            _siraLog.Debug($"Switching to {platform.name}");
            _environmentHider.HideObjectsForPlatform(platform);
            SpawnPlatform(platform.gameObject);
        }
        private void CancelCurrentExecutions()
        {
            try
            {
                _logger.LogTrace("Marking consumer executions as cancelled");
                _cancellationTokenSource?.Cancel();
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Unable to cancel consumer");
            }

            try
            {
                _cancellationTokenSource?.Dispose();
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Unable to dispose cancellation token source");
            }
            finally
            {
                _cancellationTokenSource = null;
            }
        }
Beispiel #21
0
        private void OnSlackChanged()
        {
            // Cancel previous task if any
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();

            // Wait previous task to complete
            if (_updateTask != null)
            {
                Task.WaitAny(_updateTask);
            }

            // Prepare new token
            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;

            // Determine delay before task execution
            // We want to shutdown light immediately but wait in other cases to avoid blinks
            var currentWeight = GetWeight();
            var delay         = currentWeight > _previousWeight ? DelayBeforeUpdate : 0;

            _previousWeight = currentWeight;

            _updateTask = Task
                          .Delay(delay, token)
                          .ContinueWith(UpdateLuxaforAsync, token);
        }
        public void Cancel時にRegisterで登録したデリゲートが呼ばれる()
        {
            var runner = new SampleTaskRunner.TaskRunner();

            {
                // キャンセルしない場合
                var cts = new CancellationTokenSource();
                var t = new Task<string>(c => Cancelで戻り値が切り替わるコルーチン(10, c, cts.Token));
                t.Start(runner);
                runner.Update(20);

                Assert.IsTrue(t.IsCompleted);
                Assert.AreEqual(CompletedMessage, t.Result);
            }

            {
                // キャンセルする場合
                var cts = new CancellationTokenSource();
                var t = new Task<string>(c => Cancelで戻り値が切り替わるコルーチン(10, c, cts.Token));
                t.Start(runner);
                runner.Update(5);
                cts.Cancel();
                runner.Update(5);

                Assert.IsTrue(t.IsCompleted);
                Assert.AreEqual(CanceledMessage, t.Result);
            }
        }
Beispiel #23
0
    static int Main(string[] args)
    {
        SemaphoreSlim s = new SemaphoreSlim(initialCount: 1);

        var cts = new CancellationTokenSource();
        s.Wait();
        var t = s.WaitAsync(cts.Token);
        s.Release();
        cts.Cancel();


        if (t.Status != TaskStatus.Canceled && s.CurrentCount == 0)
        {
            Console.WriteLine("PASS");
            return 100;
        }
        else
        {
            Console.WriteLine("FAIL");
            Console.WriteLine("Expected task status to not be Canceled and s.CurrentCount == 0");
            Console.WriteLine("Actual: Task: " + t.Status + "; CurrentCount: " + s.CurrentCount);
            return 101;
        }


    }
Beispiel #24
0
        public async Task DeleteAsync(DomainId id)
        {
            var job = state.Value.Jobs.FirstOrDefault(x => x.Id == id);

            if (job == null)
            {
                throw new DomainObjectNotFoundException(id.ToString());
            }

            if (currentJob == job)
            {
                try
                {
                    currentJobToken?.Cancel();
                }
                catch (ObjectDisposedException)
                {
                    return;
                }
            }
            else
            {
                await RemoveAsync(job);
            }
        }
Beispiel #25
0
        private async Task RefreshDataAsync()
        {
            _refreshCts?.Cancel();
            _refreshCts = new CancellationTokenSource();

            var cancellationToken = _refreshCts.Token;
            var request           = new ItemsProviderRequest(_itemsBefore, _visibleItemCapacity, cancellationToken);

            try
            {
                var result = await _itemsProvider(request);

                // Only apply result if the task was not canceled.
                if (!cancellationToken.IsCancellationRequested)
                {
                    _itemCount             = result.TotalItemCount;
                    _loadedItems           = result.Items;
                    _loadedItemsStartIndex = request.StartIndex;

                    StateHasChanged();
                }
            }
            catch (Exception e)
            {
                if (e is OperationCanceledException oce && oce.CancellationToken == cancellationToken)
                {
                    // No-op; we canceled the operation, so it's fine to suppress this exception.
                }
    static void Main(string[] args)
    {
        var cts = new CancellationTokenSource();
        var ct = cts.Token;

        Task task1 = new Task(() => { Run1(ct); }, ct);

        Task task2 = new Task(Run2);

        try
        {
            task1.Start();
            task2.Start();

            Thread.Sleep(1000);

            cts.Cancel();

            Task.WaitAll(task1, task2);
        }
        catch (AggregateException ex)
        {
            foreach (var e in ex.InnerExceptions)
            {
                Console.WriteLine("\nhi,我是OperationCanceledException:{0}\n", e.Message);
            }

            //task1是否取消
            Console.WriteLine("task1是不是被取消了? {0}", task1.IsCanceled);
            Console.WriteLine("task2是不是被取消了? {0}", task2.IsCanceled);
        }

        Console.Read();
    }
Beispiel #27
0
        public Task LeaveRoom()
        {
            // The join may have not completed yet, so certain tasks that either update the room or reference the room should be cancelled.
            // This includes the setting of Room itself along with the initial update of the room settings on join.
            joinCancellationSource?.Cancel();

            // Leaving rooms is expected to occur instantaneously whilst the operation is finalised in the background.
            // However a few members need to be reset immediately to prevent other components from entering invalid states whilst the operation hasn't yet completed.
            // For example, if a room was left and the user immediately pressed the "create room" button, then the user could be taken into the lobby if the value of Room is not reset in time.
            var scheduledReset = scheduleAsync(() =>
            {
                APIRoom = null;
                Room    = null;
                CurrentMatchPlayingItem.Value = null;
                PlayingUserIds.Clear();

                RoomUpdated?.Invoke();
            });

            return(joinOrLeaveTaskChain.Add(async() =>
            {
                await scheduledReset.ConfigureAwait(false);
                await LeaveRoomInternal().ConfigureAwait(false);
            }));
        }
Beispiel #28
0
    private void CancelRequestAbortedToken()
    {
        ThreadPool.UnsafeQueueUserWorkItem(ctx =>
        {
            try
            {
                CancellationTokenSource?localAbortCts = null;

                lock (ctx._abortLock)
                {
                    if (ctx._abortedCts != null)
                    {
                        localAbortCts   = ctx._abortedCts;
                        ctx._abortedCts = null;
                    }
                }

                // If we cancel the cts, we don't dispose as people may still be using
                // the cts. It also isn't necessary to dispose a canceled cts.
                localAbortCts?.Cancel();
            }
            catch (Exception ex)
            {
                Log.ApplicationError(_logger, ((IHttpConnectionFeature)this).ConnectionId, TraceIdentifier !, ex);    // TODO: Can TraceIdentifier be null?
            }
        }, this, preferLocal: false);
    }
Beispiel #29
0
 public void StopDownload()
 {
     if (Isloading)
     {
         _cancellationToken?.Cancel();
     }
 }
Beispiel #30
0
 public static void Main(String[] args)
 {
     Console.WriteLine("\n-- Cancellation with acknowledgement -------------");
     {
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = Task.Run(() => ComputeTaskWithAcknowledgement(token), token);
       Thread.Sleep(0);  // Allow task to be scheduled
       Console.WriteLine(task.Status);   // Running
       cts.Cancel();
       Thread.Sleep(0);
       Console.WriteLine(task.Status);   // Canceled
       try {
     task.Wait();    // Throws AggregateException containing TaskCanceledException
       } catch (Exception exn) {
     Console.WriteLine("Caught " + exn);
       }
       Console.WriteLine(task.Status);   // Canceled
     }
     Console.WriteLine("\n-- Cancellation without acknowledgement ----------");
     {
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = Task.Run(() => ComputeTaskWithoutAcknowledgement(token), token);
       Thread.Sleep(0);
       Console.WriteLine(task.Status);   // Running
       cts.Cancel();
       Console.WriteLine(task.Status);   // Running
       task.Wait();
       Console.WriteLine(task.Status);   // RanToCompletion
     }
     Console.WriteLine("\n-- Cancellation before Start ---------------------");
     {
       // Cancel before running
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = new Task(delegate { }, token);
       Console.WriteLine(task.Status);   // Created
       cts.Cancel();
       Console.WriteLine(task.Status);   // Canceled
       try {
     task.Start();   // Throws InvalidOperationException
       } catch (Exception exn) {
     Console.WriteLine("Caught " + exn);
       }
       Console.WriteLine(task.Status);   // Canceled
     }
     Console.WriteLine("\n-- Completing before cancellation ----------------");
     {
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = new Task(delegate { }, token);
       Console.WriteLine(task.Status);   // Created
       task.Start();
       Thread.Sleep(0);  // Allow task to be scheduled
       Console.WriteLine(task.Status);   // RanToCompletion
       cts.Cancel();
       Console.WriteLine(task.Status);   // RanToCompletion
     }
 }
Beispiel #31
0
        private void _runDelayedCheck()
        {
            _checkTimerCancel?.Cancel();
            _checkTimerCancel = new CancellationTokenSource();

            Timer.Spawn(DeadCheckDelay, _checkForWinner, _checkTimerCancel.Token);
        }
Beispiel #32
0
    public static void Main(){

        CancellationTokenSource cancelTokenSrc = new CancellationTokenSource();
        
        Task<Int32> t = new Task<Int32>( 
            () => { return Sum(100000000, cancelTokenSrc.Token);},
            cancelTokenSrc.Token);       
        
        t.Start();
        
        cancelTokenSrc.Cancel();
        
        Thread.Sleep(1000);
        
        try{
            Console.WriteLine("Waiting...............");
            t.Wait(); 
        }catch(AggregateException ex){        
            ex.Handle(x=> { Console.WriteLine(x.ToString()); return true;});
        } 
        try{
            Console.WriteLine("Extracting Result");
            Console.WriteLine("The Sum is: " + t.Result); // An Int32 value            
        }catch(AggregateException ex){        
            ex.Handle(x=> { Console.WriteLine(x.ToString()); return true;});
        }
    }
Beispiel #33
0
    public async Task BuildPrivacySuggestionsAsync(Wallet wallet, TransactionInfo info, BitcoinAddress destination, BuildTransactionResult transaction, bool isFixedAmount, CancellationToken cancellationToken)
    {
        _suggestionCancellationTokenSource?.Cancel();
        _suggestionCancellationTokenSource?.Dispose();

        _suggestionCancellationTokenSource      = new(TimeSpan.FromSeconds(15));
        using CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_suggestionCancellationTokenSource.Token, cancellationToken);

        Suggestions.Clear();
        SelectedSuggestion = null;

        if (!info.IsPrivate)
        {
            Suggestions.Add(new PocketSuggestionViewModel(SmartLabel.Merge(transaction.SpentCoins.Select(x => x.GetLabels(wallet.KeyManager.MinAnonScoreTarget)))));
        }

        var loadingRing = new LoadingSuggestionViewModel();

        Suggestions.Add(loadingRing);

        var hasChange = transaction.InnerWalletOutputs.Any(x => x.ScriptPubKey != destination.ScriptPubKey);

        if (hasChange && !isFixedAmount && !info.IsPayJoin)
        {
            var suggestions =
                ChangeAvoidanceSuggestionViewModel.GenerateSuggestionsAsync(info, destination, wallet, linkedCts.Token);

            await foreach (var suggestion in suggestions)
            {
                Suggestions.Insert(Suggestions.Count - 1, suggestion);
            }
        }

        Suggestions.Remove(loadingRing);
    }
Beispiel #34
0
    internal static void Start()
    {
        foreach (var item in Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll", new EnumerationOptions
        {
            RecurseSubdirectories = true,
        }))
        {
            try
            {
                Assembly.LoadFrom(item);
            }
            catch { }
        }

        try
        {
            cts = new();
            var builder = Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder();
            ConfigureWebHost(builder.WebHost);
            host = builder.Build();
            host.RunAsync(cts.Token);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            cts?.Cancel();
        }
Beispiel #35
0
        private async Task RemovePackageAsync(IEnumerable <string>?assemblyNames)
        {
            try
            {
                IsLoading = true;
                _removeCancellationTokenSource?.Cancel();
                _removeCancellationTokenSource = new CancellationTokenSource();

                var removeTask = Task.Run(async() =>
                {
                    var assemblies = assemblyNames ?? (await _assembliesService.RequireAllAssembliesAsync()).Select(a => a.Name);
                    return(await _localPackagesService.RemovePackageAsync(_selectedPackage !.Value.Id, assemblies));
                }, _removeCancellationTokenSource.Token);

                var successRemove = await DialogHelper.ShowLoadingAsync("Removing", "Please wait while package removing...", removeTask);

                if (successRemove)
                {
                    PackageInstalledOrRemoved?.Invoke();
                    await ChangeSelectedPackageRowAsync(_selectedPackage !.Value);
                }
                else
                {
                    DialogHelper.ShowErrorAlert($"Failed to remove package {_selectedPackage!.Value.Id}");
                }
            }
            finally
            {
                IsLoading = false;
            }
        }
        public async Task StopAsync()
        {
            // Signal the CTS to give a hint to the server thread that it is time to close up shop.
            _cts?.Cancel();

            try
            {
                if (_task == null)
                {
                    return; // Never started.
                }
                // This will re-throw any exception that was caught on the StartServerAsync thread.
                // Perhaps not ideal behavior but hey, if the implementation does not want this to happen
                // it should have caught it itself in the background processing thread.
                await _task;
            }
            catch (OperationCanceledException)
            {
                // We'll eat this one, though, since it can easily get thrown by whatever checks the CancellationToken.
            }
            finally
            {
                _cts?.Dispose();
                _cts = null;
            }
        }
Beispiel #37
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)
                    if (webView != null)
                    {
                        cts?.Cancel();
                        webView.DocumentTitleChanged -= WebView_DocumentTitleChanged;
                        webView.LoadingStateChange   -= WebView_LoadingStateChange;
                        if (DataContext is WebView3WindowViewModel vm)
                        {
                            webView.OnStreamResponseFilterResourceLoadComplete -= vm.OnStreamResponseFilterResourceLoadComplete;
                        }
                        ((IDisposable)webView).Dispose();
                    }
                    if (DataContext is IDisposable d)
                    {
                        d.Dispose();
                    }
                }

                // TODO: 释放未托管的资源(未托管的对象)并替代终结器
                // TODO: 将大型字段设置为 null
                disposedValue = true;
            }
        }
Beispiel #38
0
 private void CallbackHubCanceled(object?sender, string e)
 {
     if (_connection.CallId == e || string.IsNullOrEmpty(e))
     {
         _cts?.Cancel();
     }
 }
        private async Task DeadlineExceededAsync()
        {
            if (!TryStartExceededDeadline())
            {
                return;
            }

            try
            {
                await _serverCallContext.DeadlineExceededAsync();

                lock (this)
                {
                    IsCallComplete = true;
                }

                // Canceling CTS will trigger registered callbacks.
                // Exception could be thrown from them.
                _deadlineCts?.Cancel();
            }
            catch (Exception ex)
            {
                GrpcServerLog.DeadlineCancellationError(_serverCallContext.Logger, ex);
            }
            finally
            {
                _deadlineExceededCompleteTcs !.TrySetResult(null);
            }
        }
Beispiel #40
0
        public void Precancellation()
        {
            IReadableChannel<int> c = Channel.CreateFromTask(Task.FromResult(42));

            var cts = new CancellationTokenSource();
            cts.Cancel();

            AssertSynchronouslyCanceled(c.WaitToReadAsync(cts.Token), cts.Token);
            AssertSynchronouslyCanceled(c.ReadAsync(cts.Token).AsTask(), cts.Token);
        }
        public async Task Cancel_UnpartneredRead_ThrowsCancellationException()
        {
            IChannel<int> c = Channel.CreateUnbuffered<int>();
            var cts = new CancellationTokenSource();

            Task r = c.ReadAsync(cts.Token).AsTask();
            Assert.False(r.IsCompleted);

            cts.Cancel();
            await AssertCanceled(r, cts.Token);
        }
        public async Task Cancel_UnpartneredWrite_ThrowsCancellationException()
        {
            IChannel<int> c = Channel.CreateUnbuffered<int>();
            var cts = new CancellationTokenSource();

            Task w = c.WriteAsync(42, cts.Token);
            Assert.False(w.IsCompleted);

            cts.Cancel();
            await AssertCanceled(w, cts.Token);
        }
    /// <summary>
    /// Disposes the test class instance. Sends the <see cref="ITestClassDisposeStarting"/> and <see cref="ITestClassDisposeFinished"/>
    /// messages as appropriate.
    /// </summary>
    /// <param name="test">The test</param>
    /// <param name="testClass">The test class instance to be disposed</param>
    /// <param name="messageBus">The message bus used to send the test messages</param>
    /// <param name="timer">The timer used to measure the time taken for construction</param>
    /// <param name="cancellationTokenSource">The cancellation token source</param>
    public static void DisposeTestClass(this ITest test,
                                        object testClass,
                                        IMessageBus messageBus,
                                        ExecutionTimer timer,
                                        CancellationTokenSource cancellationTokenSource)
    {
        var disposable = testClass as IDisposable;
        if (disposable == null)
            return;

        if (!messageBus.QueueMessage(new TestClassDisposeStarting(test)))
            cancellationTokenSource.Cancel();

        try
        {
            timer.Aggregate(disposable.Dispose);
        }
        finally
        {
            if (!messageBus.QueueMessage(new TestClassDisposeFinished(test)))
                cancellationTokenSource.Cancel();
        }
    }
        public static async Task TimeoutAfter(this Task task, int millisecondsTimeout)
        {
            var cts = new CancellationTokenSource();

            if (task == await Task.WhenAny(task, Task.Delay(millisecondsTimeout, cts.Token)))
            {
                cts.Cancel();
                await task;
            }
            else
            {
                throw new TimeoutException();
            }
        }
        public static void CancelBeforeWait()
        {
            SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2);

            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(millisec, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(timeSpan, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            semaphoreSlim.Dispose();
        }
        public static void BarrierCancellationTestsCancelAfterWait()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            const int numberParticipants = 3;
            Barrier barrier = new Barrier(numberParticipants);

            Task.Run(() => cancellationTokenSource.Cancel());

            //Test that backout occurred.
            Assert.Equal(numberParticipants, barrier.ParticipantsRemaining);

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually
        }
    public static void Main(){
        Task parent = new Task(() => 
	    {
                var cts = new CancellationTokenSource ();
                var tf  = new TaskFactory<Int32> (cts.Token, 
						  TaskCreationOptions.AttachedToParent,
                                                  TaskContinuationOptions.ExecuteSynchronously, 
						  TaskScheduler.Default);

                // This task creates and starts 3 child tasks
                var childTasks = new[] {
                    tf.StartNew(() => Sum(cts.Token, 10000)),
                    tf.StartNew(() => Sum(cts.Token, 20000)),
                    tf.StartNew(() => Sum(cts.Token, Int32.MaxValue))  // Too big, throws OverflowException
                };

                // If any of the child tasks throw, cancel the rest of them
                for (Int32 task = 0; task < childTasks.Length; task++)
                    childTasks[task].ContinueWith (t => cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);

                // When all children are done, get the maximum value returned from the
                // non-faulting/canceled tasks. Then pass the maximum value to another
                // task that displays the maximum result
                tf.ContinueWhenAll (childTasks, completedTasks => completedTasks.Where(t => t.Status == TaskStatus.RanToCompletion).Max(t => t.Result), 
                                    CancellationToken.None)
                .ContinueWith(t =>Console.WriteLine("The maximum is: " + t.Result),
                              TaskContinuationOptions.ExecuteSynchronously);
            });

        // When the children are done, show any unhandled exceptions too
        parent.ContinueWith(p => {
                // I put all this text in a StringBuilder and call Console.WriteLine just once
                // because this task could execute concurrently with the task above & I don't
                // want the tasks' output interspersed
                StringBuilder sb = new StringBuilder(
                    "The following exception(s) occurred:" + Environment.NewLine);

                foreach (var e in p.Exception.Flatten().InnerExceptions)
                    sb.AppendLine("   "+ e.GetType().ToString());
                Console.WriteLine(sb.ToString());
            }, TaskContinuationOptions.OnlyOnFaulted);

        // Start the parent Task so it can start its children
        parent.Start();
        Thread.Sleep(1000);
    }
        public static void CancelBeforeWait()
        {
            ManualResetEventSlim mres = new ManualResetEventSlim();
            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);

            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(millisec, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(timeSpan, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            mres.Dispose();
        }
        public static void CancelAfterWait()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            CountdownEvent countdownEvent = new CountdownEvent(2); ;  // countdownEvent that will block all waiters

            Task.Run(() =>
            {
                cancellationTokenSource.Cancel();
            });

            //Now wait.. the wait should abort and an exception should be thrown
            EnsureOperationCanceledExceptionThrown(() => countdownEvent.Wait(cancellationToken), cancellationToken,
               "CancelAfterWait:  An OCE(null) should have been thrown that references the cancellationToken.");

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually
        }
    void Main(){

        Console.WriteLine("Starting Main Thread");

        CancellationTokenSource clsTokenSrc = new CancellationTokenSource();

        ThreadPool.QueueUserWorkItem(
            x=>AsyncOperation1(clsTokenSrc.Token, 10000000));

        Thread.Sleep(5);
        Console.WriteLine("Cancelling AsyncOperation from Main Thread");
        clsTokenSrc.Cancel();
        Thread.Sleep(1);

        Console.WriteLine("AsyncOperation is cancelled from Main Thread");
        Thread.Sleep(1000);

        Console.WriteLine("Exiting Main Thread");
    }
        public static void BarrierCancellationTestsCancelAfterWait_Negative()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            const int numberParticipants = 3;
            Barrier barrier = new Barrier(numberParticipants);

            Task.Run(() => cancellationTokenSource.Cancel());

            //Now wait.. the wait should abort and an exception should be thrown
            EnsureOperationCanceledExceptionThrown(
               () => barrier.SignalAndWait(cancellationToken),
               cancellationToken,
               "CancelAfterWait:  An OCE(null) should have been thrown that references the cancellationToken.");

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually
        }
Beispiel #52
0
    public static int Main(string[] args)
    {
        var cts = new CancellationTokenSource();
        var t = new Task<int>(() => Sum(cts.Token, 1000), cts.Token);
        t.Start();
        cts.Cancel();

        try
        {
            Console.WriteLine("The sum is : {0}", t.Result);
        }
        catch(AggregateException ae)
        {
            ae.Handle(e => e is OperationCanceledException);
            Console.WriteLine("Sum was canceled");
        }

        return 0;
    }
Beispiel #53
0
    public static void Main(){
        CancellationTokenSource cts = new CancellationTokenSource();
        Task<Int32> t = Task.Run(() => Sum(cts.Token, 1000000000), cts.Token);

        // Sometime later, cancel the CancellationTokenSource to cancel the Task
        cts.Cancel(); // This is an asynchronous request, the Task may have completed already

        try {
            // If the task got canceled, Result will throw an AggregateException
            Console.WriteLine("The sum is: " + t.Result);   // An Int32 value
        }catch (AggregateException x) {
            // Consider any OperationCanceledException objects as handled.
            // Any other exceptions cause a new AggregateException containing
            // only the unhandled exceptions to be thrown
            //x.Handle(e => e is OperationCanceledException);
            x.Handle(e => {Console.WriteLine(e.ToString()); return true;} );

            // If all the exceptions were handled, the following executes
            Console.WriteLine("Sum was canceled");
        }
    }
    public static void Main(){
        

        CancellationTokenSource clsTokenSrc = new CancellationTokenSource();

        Task<Int32> task = new Task<Int32>( () =>{ return Sum(100000000, clsTokenSrc.Token); } , clsTokenSrc.Token);

        task.Start();

        clsTokenSrc.Cancel();

       
        task.ContinueWith(t => { Console.WriteLine(t.Result); },  
                          TaskContinuationOptions.OnlyOnRanToCompletion);        

        task.ContinueWith( 
            t => 
            { 
                AggregateException ex = (t.Exception as AggregateException);
                ex.Handle( x => 
                    { 
                        Console.WriteLine("Exception catched in Main:{0}", x.ToString());
                        return true;
                    });
            },
            TaskContinuationOptions.OnlyOnFaulted);    
        
        task.ContinueWith(t => 
            { 
                Console.WriteLine("Task Cancelled ");
            },
            TaskContinuationOptions.OnlyOnCanceled);
        
        while(task.IsCompleted)
        {            
            Thread.Sleep(1);
        }
    }
        public static void BarrierCancellationTestsCancelBeforeWait()
        {
            Barrier barrier = new Barrier(3);

            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);

            EnsureOperationCanceledExceptionThrown(
               () => barrier.SignalAndWait(ct), ct,
               "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(
               () => barrier.SignalAndWait(millisec, ct), ct,
               "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(
               () => barrier.SignalAndWait(timeSpan, ct), ct,
               "CancelBeforeWait:  An OCE should have been thrown.");

            barrier.Dispose();
        }
Beispiel #56
0
        public void Run()
        {
            var cts = new CancellationTokenSource();

            for (int i=0; i<10; i++)
            {
                WaitCallback wc = (s) => {
                    var token = (CancellationTokenSource)s;
                    for (int j=0; j<50; j++)
                    {
                        if (token.IsCancellationRequested)
                            return;

                        Console.WriteLine("Output");
                        token.WaitHandle.WaitOne(1000);
                    }
                };

                ThreadPool.QueueUserWorkItem(wc, cts.Token);

                cts.Cancel();
            }
        }
        public static void CancelAfterWait()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            ManualResetEventSlim mres = new ManualResetEventSlim();

            Task.Run(
                () =>
                {
                    for (int i = 0; i < 400; i++) ;
                    cancellationTokenSource.Cancel();
                }
                );

            //Now wait.. the wait should abort and an exception should be thrown
            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(cancellationToken), cancellationToken,
               "CancelBeforeWait:  An OCE(null) should have been thrown that references the cancellationToken.");

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually
        }
 private static IEnumerable<Task<object>> CancelingTaskEnumerable_Generic(List<string> log, CancellationTokenSource cts)
 {
     log.Add("first");
     yield return Task.Factory.StartNew(() =>
     {
         log.Add("Executing first task. Log size: " + log.Count);
         cts.Cancel();
         return (object)null;
     });
     log.Add("second");
     yield return Task.Factory.StartNew(() =>
     {
         log.Add("Executing second task. Log size: " + log.Count);
         return (object)null;
     });
 }
        public void RunSynchronously_Cancels()
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.Cancel();

            Task t = TaskHelpers.RunSynchronously(() => { throw new InvalidOperationException(); }, cts.Token);
            Assert.Throws<TaskCanceledException>(() => t.Wait());
        }
Beispiel #60
0
        public static IEnumerable<object[]> CanceledTasksAndExpectedCancellationExceptions()
        {
            var cts = new CancellationTokenSource();
            var oce = new OperationCanceledException(cts.Token);

            // Scheduled Task
            Task<int> generic = Task.Run<int>(new Func<int>(() =>
            {
                cts.Cancel();
                throw oce;
            }), cts.Token);
            yield return new object[] { LineNumber(), generic, oce };

            Task nonGeneric = generic;

            // WhenAll Task and Task<int>
            yield return new object[] { LineNumber(), Task.WhenAll(generic), oce };
            yield return new object[] { LineNumber(), Task.WhenAll(generic, Task.FromResult(42)), oce };
            yield return new object[] { LineNumber(), Task.WhenAll(Task.FromResult(42), generic), oce };
            yield return new object[] { LineNumber(), Task.WhenAll(generic, generic, generic), oce };
            yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric), oce };
            yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric, Task.FromResult(42)), oce };
            yield return new object[] { LineNumber(), Task.WhenAll(Task.FromResult(42), nonGeneric), oce };
            yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric, nonGeneric, nonGeneric), oce };

            // Task.Run Task and Task<int> with unwrapping
            yield return new object[] { LineNumber(), Task.Run(() => generic), oce };
            yield return new object[] { LineNumber(), Task.Run(() => nonGeneric), oce };

            // A FromAsync Task and Task<int>
            yield return new object[] { LineNumber(), Task.Factory.FromAsync(generic, new Action<IAsyncResult>(ar => { throw oce; })), oce };
            yield return new object[] { LineNumber(), Task<int>.Factory.FromAsync(nonGeneric, new Func<IAsyncResult, int>(ar => { throw oce; })), oce };

            // AsyncTaskMethodBuilder
            var atmb = new AsyncTaskMethodBuilder();
            atmb.SetException(oce);
            yield return new object[] { LineNumber(), atmb.Task, oce };
        }