예제 #1
0
 public void Cancel()
 {
     if (InProgress)
     {
         CancellationSource.Cancel();
     }
 }
예제 #2
0
 protected virtual void CancelAttemptIfBusy()
 {
     if (IsBusy)
     {
         CancellationSource?.Cancel();
     }
 }
예제 #3
0
        public async Task DoesNotCauseFatalExceptionWhenCancelWhileDelayed()
        {
            executionStrategy.Setup(o => o.ExecuteAsync(It.IsAny <Action <IProducerConsumerContext <object> > >(), It.IsAny <CancellationToken>()))
            .Returns <Action <IProducerConsumerContext <object> >, CancellationToken>((context, cancellationToken) =>
            {
                Task.Delay(1000, cancellationToken).GetAwaiter().GetResult();

                return(Task.FromResult(false));
            });

            scheduler.Setup(o => o.CalculateNextExecution(It.IsAny <DateTimeOffset>(), It.IsAny <DateTimeOffset>()))
            .Returns(DateTimeOffset.Now.AddMinutes(1));

            using var cancellationSource = new CancellationSource();
            using var target             = new TestableScheduledProducerEngine(executionStrategy.Object, cancellationSourceFactory.Object, errorHandler.Object, scheduler.Object, new ScheduledEngineOptions());

            cancellationSourceFactory.Setup(o => o.Create(It.IsAny <CancellationToken>())).Returns(cancellationSource);

            target.Initialize(context => { }, CancellationToken.None);

            target.SetDelayCallback(() =>
            {
                cancellationSource.RequestImmediateCancellation();
            });

            await target.StartAsync();

            await target.WaitForCompletionAsync();

            errorHandler.Verify(o => o.Handle(It.IsAny <Exception>(), ErrorSeverityLevel.Fatal), Times.Never);
        }
예제 #4
0
 public void CloseLoadDetectionView(object sender, EventArgs e)
 {
     if (CancelTokenDisposed == false)
     {
         CancellationSource.Cancel();
     }
 }
예제 #5
0
 private void toolStripButton1_Click(object sender, EventArgs e)
 {
     if (CancellationSource != null)
     {
         CancellationSource.Cancel();
     }
 }
예제 #6
0
        private async Task HideToast(ContentPage currentPage, bool removeContainer)
        {
            CancellationSource.Cancel();

            // get toast view, can be only one or none
            var toastContainer = FindByName(currentPage.Id.ToString());

            if (!(toastContainer?.Children.FirstOrDefault(w => w.GetType() == typeof(ToastView)) is ToastView toast))
            {
                // remove container
                if (removeContainer)
                {
                    UnregisterName(currentPage.Id.ToString());
                }

                return;
            }

            // animate toast
            if (toast.ToastOptions.OnBeforeHidingToast != null)
            {
                await toast.ToastOptions.OnBeforeHidingToast(toast);
            }

            // remove toast
            toastContainer.Children.Remove(toast);

            // remove container
            if (removeContainer)
            {
                UnregisterName(currentPage.Id.ToString());
            }
        }
        public async Task CloseAsync(string message, WebSocketCloseStatus status = WebSocketCloseStatus.NormalClosure)
        {
            if (Socket == null)
            {
                return;
            }

            Task receiveTask = ReceiveLoop.StopAsync();

            try
            {
                using var closeToken = new CancellationTokenSource(TimeSpan.FromSeconds(3));
                await Socket?.CloseAsync(status, message, closeToken.Token);
            }
            catch (Exception e)
            {
                Console.WriteLine(String.Format("Exception while closing : {0}", e.ToString()));
            }
            finally
            {
                CancellationSource?.Cancel();
                Socket?.Dispose();
                Socket = null;
                CancellationSource?.Dispose();
                CancellationSource = null;
            }
        }
예제 #8
0
 public void FoundAdapterById(
     string adapterId,
     IObjectPrx?proxy,
     bool isReplicaGroup,
     Current current,
     CancellationToken cancel)
 {
     if (isReplicaGroup)
     {
         lock (_mutex)
         {
             _proxies.Add(proxy !);
             if (_proxies.Count == 1)
             {
                 // Cancel the request timeout and let InvokeAsync wait for additional replies from the replica
                 // group
                 CancellationSource.Cancel();
             }
         }
     }
     else
     {
         CompletionSource.SetResult(proxy);
     }
 }
예제 #9
0
 protected override void OnCancelClicked(EventArgs e)
 {
     base.OnCancelClicked(e);
     WasCanceled = true;
     CancelState = ButtonMode.Disabled;
     CancellationSource.Cancel();
 }
        public void TestMedium()
        {
            var f = Files.pf_large3;
            var l = new LargeFileGenerator(1_000, 1986);

            l.Generate();
            l.Store(f);

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            Client.TextDocument.DidOpen(f, "dfy");

            CompilerParams p = new CompilerParams
            {
                CompilationArguments = new string[] { },
                FileToCompile        = f
            };

            CancellationSource.CancelAfter(TimeSpan.FromMinutes(1));

            Client.SendRequest <CompilerResults>("compile", p, CancellationSource.Token).Wait();

            stopwatch.Stop();

            var elapsed_time = stopwatch.ElapsedMilliseconds;

            Console.WriteLine($"Performancetest 2 with 1'000 LOC took {elapsed_time}ms");
            Assert.Less(elapsed_time, 60e3, "Runtime takes too long! Was: " + elapsed_time);
        }
예제 #11
0
        private void SetUpCancellationSource(RasDialContext context)
        {
            CancellationSource?.Dispose();
            CancellationSource = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken);

            // Ensures that the connection can be cancelled even if the callback is stuck.
            CancellationSource.Token.Register(() => OnCancellationRequestedCallback(context));
        }
예제 #12
0
        public async Task ExecDefaultContainerStdOut()
        {
            if (!Debugger.IsAttached)
            {
                CancellationSource.CancelAfter(
                    TimeSpan.FromSeconds(5));
            }

            await Host.StartAsync(TestCancellation).ConfigureAwait(false);

            using (Kubernetes client = CreateTestClient())
            {
                testOutput.WriteLine("Invoking exec operation...");

                WebSocket clientSocket = await client.WebSocketNamespacedPodExecAsync(
                    "mypod",
                    "mynamespace",
                    new string[] { "/bin/bash" },
                    "mycontainer",
                    false,
                    false,
                    true,
                    webSocketSubProtol : WebSocketProtocol.ChannelWebSocketProtocol,
                    cancellationToken : TestCancellation).ConfigureAwait(false);

                Assert.Equal(
                    WebSocketProtocol.ChannelWebSocketProtocol,
                    clientSocket.SubProtocol); // For WebSockets, the Kubernetes API defaults to the binary channel (v1) protocol.

                testOutput.WriteLine(
                    $"Client socket connected (socket state is {clientSocket.State}). Waiting for server-side socket to become available...");

                WebSocket serverSocket = await WebSocketTestAdapter.AcceptedPodExecV1Connection;
                testOutput.WriteLine(
                    $"Server-side socket is now available (socket state is {serverSocket.State}). Sending data to server socket...");

                const int    STDOUT         = 1;
                const string expectedOutput = "This is text send to STDOUT.";

                int bytesSent = await SendMultiplexed(serverSocket, STDOUT, expectedOutput).ConfigureAwait(false);

                testOutput.WriteLine($"Sent {bytesSent} bytes to server socket; receiving from client socket...");

                (string receivedText, byte streamIndex, int bytesReceived) = await ReceiveTextMultiplexed(clientSocket).ConfigureAwait(false);

                testOutput.WriteLine(
                    $"Received {bytesReceived} bytes from client socket ('{receivedText}', stream {streamIndex}).");

                Assert.Equal(STDOUT, streamIndex);
                Assert.Equal(expectedOutput, receivedText);

                await Disconnect(clientSocket, serverSocket,
                                 WebSocketCloseStatus.NormalClosure,
                                 "Normal Closure").ConfigureAwait(false);

                WebSocketTestAdapter.CompleteTest();
            }
        }
예제 #13
0
        private async Task HideToastIn(int timeInMilliseconds)
        {
            CancellationSource.Cancel();
            CancellationSource = new CancellationTokenSource();

            await Task.Delay(timeInMilliseconds, CancellationSource.Token);

            await HideToast();
        }
예제 #14
0
 private void ButtonStop_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         CancellationSource?.Cancel();
         Logger.Log("Завершение операций...");
     }
     catch (Exception ex)
     {
         Logger.ErrorLog(ex);
     }
 }
예제 #15
0
 public void Dispose()
 {
     CancellationSource.Cancel();
     try
     {
         client?.Close();
     }
     catch (CommunicationException)
     {
         client?.Abort();
     }
 }
예제 #16
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                CancelAttemptIfBusy();

                CancellationSource?.Dispose();
                callbackHandler.Dispose();
            }

            base.Dispose(disposing);
        }
예제 #17
0
        protected override void Free(bool disposing)
        {
            if (CancellationSource != null)
            {
                CancellationSource.Cancel();
            }

            if (Event != null)
            {
                Event.WaitOne(200, false);
                Event.Dispose();
                Event = null;
            }
            ReleaseLogWriter();
        }
예제 #18
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (IsBusy)
                {
                    CancellationSource.Cancel();
                }

                CancellationSource?.Dispose();
                callbackHandler.Dispose();
            }

            base.Dispose(disposing);
        }
예제 #19
0
        private void Window_Closing(object sender, CancelEventArgs e)
        {
            try
            {
                CancellationSource?.Cancel();

                if (CurrentProfile.ProfileName != null)
                {
                    XmlSettingsWrite(CurrentProfile.ProfileName);
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorLog(ex);
            }
        }
예제 #20
0
 public virtual async Task StopAsync()
 {
     if (CancellationSource != null && CancellationSource.Token.CanBeCanceled)
     {
         CancellationSource.Cancel(true);
     }
     if (Event != null)
     {
         await Task.Run(() =>
         {
             Event.WaitOne(1000, false);
             Event.Dispose();
             Event = null;
         });
     }
 }
예제 #21
0
        /// <summary>
        /// Stops updating and cleans up
        /// </summary>
        public async Task Exit(bool ForceExit = false)
        {
            // Clean up
            Connected = false;
            Synced    = false;
            CancellationSource.Cancel();
            if (Local && !Process.HasExited)
            {
                LogLine("Saving");
                await SendRequestAsync(RequestMethod.SAVE, new JObject { }, out JObject Result);

                if (ForceExit)
                {
                    Process.Kill();
                }
            }
        }
예제 #22
0
        public async Task StartAndStopTheEngineCorrectly()
        {
            using var cancellationSource = new CancellationSource();
            using var target             = new ScheduledProducerEngine <object>(executionStrategy.Object, cancellationSourceFactory.Object, errorHandler.Object, scheduler.Object, new ScheduledEngineOptions());

            cancellationSourceFactory.Setup(o => o.Create(It.IsAny <CancellationToken>())).Returns(cancellationSource);

            target.Initialize(context => { }, CancellationToken.None);

            await target.StartAsync();

            Assert.True(target.IsRunning);

            await target.StopAsync();

            Assert.False(target.IsRunning);
        }
 /// <summary>
 /// Stops updating and cleans up
 /// </summary>
 public async Task Exit(bool ForceExit = false)
 {
     // Clean up
     Connected = false;
     Synced    = false;
     CancellationSource.Cancel();
     if (Local && !Process.HasExited)
     {
         LogLine("Saving");
         using (StreamWriter StreamWriter = Process.StandardInput)
             await StreamWriter.WriteLineAsync("exit");
         if (ForceExit)
         {
             Process.Kill();
         }
     }
 }
예제 #24
0
        private Grid GetToastContainer()
        {
            // get current page
            m_currentPageWithToast = GetCurrentContentPage();

            // try get registered toast container
            var toastContainer = FindByName(m_currentPageWithToast.Id.ToString());

            if (toastContainer != null) // found toast container
            {
                // check opened toasts, can be only one or none
                var oldToast = toastContainer.Children.FirstOrDefault(w => w.GetType() == typeof(ToastView));
                if (oldToast != null) // close old toast
                {
                    CancellationSource.Cancel();
                    toastContainer.Children.Remove(oldToast);
                }
            }
            else // no registered toast container
            {
                //Get existing toast container
                if (m_currentPageWithToast.Content is ToastContainer currentToastContainer)
                {
                    RegisterName(m_currentPageWithToast.Id.ToString(), currentToastContainer);
                    m_currentPageWithToast.Disappearing += OnPageDisappearing;
                    return(currentToastContainer);
                }

                // no any toast container
                // create and register toast container
                toastContainer = new Grid();
                RegisterName(m_currentPageWithToast.Id.ToString(), toastContainer);

                // old content
                var oldContent = m_currentPageWithToast.Content;

                // set new content
                m_currentPageWithToast.Content = toastContainer;
                toastContainer.Children.Add(oldContent);
            }

            m_currentPageWithToast.Disappearing += OnPageDisappearing;

            return(toastContainer);
        }
예제 #25
0
        public async Task RunsTheErrorHandlerWhenAnErrorHappensInStrategy()
        {
            executionStrategy.Setup(o => o.ExecuteAsync(It.IsAny <Action <IProducerConsumerContext <object> > >(), It.IsAny <CancellationToken>()))
            .ThrowsAsync(new Exception("An exception occurred"));

            using var cancellationSource = new CancellationSource();
            using var target             = new ScheduledProducerEngine <object>(executionStrategy.Object, cancellationSourceFactory.Object, errorHandler.Object, scheduler.Object, new ScheduledEngineOptions());

            cancellationSourceFactory.Setup(o => o.Create(It.IsAny <CancellationToken>())).Returns(cancellationSource);

            target.Initialize(context => { }, CancellationToken.None);

            await target.StartAsync();

            cancellationSource.RequestCancellationAfter(TimeSpan.FromSeconds(5));

            await target.WaitForCompletionAsync();

            errorHandler.Verify(o => o.Handle(It.IsAny <Exception>(), ErrorSeverityLevel.NonFatal), Times.AtLeastOnce);
        }
예제 #26
0
        public async Task RunsTheExecutionStrategy()
        {
            executionStrategy.Setup(o => o.ExecuteAsync(It.IsAny <Action <IProducerConsumerContext <object> > >(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(false);

            using var cancellationSource = new CancellationSource();
            using var target             = new ScheduledProducerEngine <object>(executionStrategy.Object, cancellationSourceFactory.Object, errorHandler.Object, scheduler.Object, new ScheduledEngineOptions());

            cancellationSourceFactory.Setup(o => o.Create(It.IsAny <CancellationToken>())).Returns(cancellationSource);

            target.Initialize(context => { }, CancellationToken.None);

            await target.StartAsync();

            cancellationSource.RequestCancellationAfter(TimeSpan.FromSeconds(5));

            await target.WaitForCompletionAsync();

            executionStrategy.Verify(o => o.ExecuteAsync(It.IsAny <Action <IProducerConsumerContext <object> > >(),
                                                         It.IsAny <CancellationToken>()), Times.AtLeastOnce);
        }
예제 #27
0
        public async Task CausesFatalExceptionWhenThrownOutsideInnerLoop()
        {
            scheduler.Setup(o => o.CalculateNextExecution(It.IsAny <DateTimeOffset>(), It.IsAny <DateTimeOffset>())).Throws <Exception>();

            using var cancellationSource = new CancellationSource();
            using var target             = new TestableScheduledProducerEngine(executionStrategy.Object, cancellationSourceFactory.Object, errorHandler.Object, scheduler.Object, new ScheduledEngineOptions());

            cancellationSourceFactory.Setup(o => o.Create(It.IsAny <CancellationToken>())).Returns(cancellationSource);

            target.Initialize(context => { }, CancellationToken.None);

            target.SetDelayCallback(() =>
            {
                cancellationSource.RequestImmediateCancellation();
            });

            await target.StartAsync();

            await target.WaitForCompletionAsync();

            errorHandler.Verify(o => o.Handle(It.IsAny <Exception>(), ErrorSeverityLevel.Fatal), Times.Once);
        }
        private void Cancel()
        {
            if (IsValid)
            {
                return;
            }

            var confirmation = new ConditionalConfirmation {
                Content = Resources.ConfirmCancellation, Title = Resources.Cancellation
            };

            CancelConfirmRequest.Raise(confirmation, x =>
            {
                if (x.Confirmed)
                {
                    CancellationSource.Cancel();

                    Result     = OperationResult.Cancelling;
                    _cancelled = true;
                    IsValid    = true;
                    CancelCommand.RaiseCanExecuteChanged();
                }
            });
        }
예제 #29
0
 public void StopMonitoring()
 {
     lock (_lock)
         CancellationSource?.Cancel();
 }
예제 #30
0
 private void SetUpCancellationSource(RasDialContext context)
 {
     CancellationSource?.Dispose();
     CancellationSource = cancellationSourceFactory.Create(context.CancellationToken);
 }