public static async Task Main()
        {
            SendThread.Start(CancellationToken.Token);
            RecieveThread.Start(CancellationToken.Token);

            Console.WriteLine("Welcome!  You can send anything to simulate a process or 'q' to quit");

            while (true)
            {
                string command = Console.ReadLine();

                if (command.ToLower() == "q")
                {
                    CancellationToken.Cancel();

                    SendThread.Join();
                    RecieveThread.Join();

                    CancellationToken.Dispose();

                    return;
                }

                Console.WriteLine(await SendData(command));
            }
        }
 public void Cancel()
 {
     ImageService.RemovePendingTask(this);
     CancellationToken.Cancel();
     Finish();
     Logger.Debug(string.Format("Canceled image generation for {0}", GetKey()));
 }
Esempio n. 3
0
        public override void OpenUserInterfaceElement(string rawDeviceList)
        {
            _parsedListCache = ParseDeviceList(rawDeviceList);
            var deleteProfilesContext = new DeleteOldProfilesPromptViewModel();

            _windowService.ShowDialog <DeleteOldProfilesPrompt>(deleteProfilesContext);

            if (!deleteProfilesContext.Result)
            {
                var msg = $"Action {ActionName} canceled by user.";
                Logger.LogMessage(msg);
                ResultConsole.AddConsoleLine(msg);
                CancellationToken.Cancel();
            }

            if (deleteProfilesContext.DayCount < 0)
            {
                var msg = $"Action {ActionName} aborted: cannot delete profiles from < 0 days..";
                Logger.LogMessage(msg);
                ResultConsole.AddConsoleLine(msg);
                CancellationToken.Cancel();
            }

            _dayCountCache = deleteProfilesContext.DayCount;
        }
Esempio n. 4
0
 /// <summary>
 /// Stop the server
 /// </summary>
 public virtual void Stop()
 {
     // send cancel token and wait for threads to end
     CancellationToken.Cancel();
     Task.WaitAll(serverTask.ToArray(), 500);
     serverTask = null;
 }
Esempio n. 5
0
        private void Disconnected(bool notified)
        {
            try
            {
                lock (_disconnectSync)
                {
                    if ((bool)_disconnectSync)
                    {
                        return;
                    }
                    _disconnectSync = true;
                }

                if (!CancellationToken.IsCancellationRequested)
                {
                    CancellationToken.Cancel();
                }

                Socket.Shutdown(SocketShutdown.Both);
                Socket.Close();

                OnConnectionClosed?.Invoke(this, new ConnectionClosedEventArgs(this, notified));

                IsConnected = false;
            }
            catch (ObjectDisposedException)
            {
                //Ok
            }
        }
Esempio n. 6
0
        /// <summary>
        ///     Disconnect client from server.
        /// </summary>
        public override async void Disconnect()
        {
            if (!Connected)
            {
                return;
            }

            CancellationToken?.Cancel();

            if (Logger.logEnabled)
            {
                if (Transport.transportDebug)
                {
                    DebugLogger.RegularDebugLog("[Client] - Shutting down.");
                }
            }

            _clientSendPoolData = null;

            if (!_serverControlled)
            {
                SendInternal(Options.ConnectionAddress, InternalMessage.Disconnect, SocketName);

                // Wait 1 seconds to make sure the disconnect message gets fired.
                await UniTask.Delay(1000);

                CloseP2PSessionWithUser(Options.ConnectionAddress, SocketName);

                Dispose();

                _connectedComplete?.TrySetResult();
            }
        }
Esempio n. 7
0
 public virtual void Remove()
 {
     ControlExtended.UIInvoke(() => ProcessManager.CurrentProcessTasks.Remove(this));
     CancellationToken?.Cancel();
     autoReset.Close();
     IsStart    = false;
     IsCanceled = true;
 }
Esempio n. 8
0
 /// <summary>
 /// Cancels progress overlay.
 /// </summary>
 public void Cancel()
 {
     try
     {
         CancellationToken.Cancel();
         Hide();
     }
     catch { }
 }
 public void Cancel()
 {
     ImageService.RemovePendingTask(this);
     CancellationToken.Cancel();
     if (Parameters.OnFinish != null)
     {
         Parameters.OnFinish(this);
     }
     Logger.Debug(string.Format("Canceled image generation for {0}", GetKey()));
 }
Esempio n. 10
0
        public override void Disconnect()
        {
            if (!Connected)
            {
                throw new ProtocolException("Connection error: Not connected to server.");
            }

            CancellationToken.Cancel();

            Stream.Disconnect();
        }
        public void Run()
        {
            CancellationToken cancellationToken = new CancellationToken();

            Foo(cancellationToken);

            Task.Run(() =>
            {
                Task.Delay(5000).Wait();
                cancellationToken.Cancel();
            });
        }
 /// <summary>
 /// Cancels the queue from processing
 /// </summary>
 /// <param name="Wait">Determines if the function should wait for the tasks to complete before returning</param>
 public void Cancel(bool Wait = false)
 {
     if (IsCompleted || IsCanceled)
     {
         return;
     }
     CancellationToken.Cancel(false);
     if (Wait)
     {
         Task.WaitAll(Tasks);
     }
 }
Esempio n. 13
0
        private async void ExecuteRunningToggle(object argument)
        {
            if (IsBusy)
            {
                RunButtonText = "Stop";

                Telemetry.TrackEvent("App.Start");
                CancellationToken = new CancellationTokenSource();

                if (LedListener == null)
                {
                    try
                    {
                        var gpio = Windows.Devices.Gpio.GpioController.GetDefault();
                        if (gpio != null)
                        {
                            Telemetry.TrackEvent("LED.Found");
                            await Log("Initialising LED listener...");

                            LedListener = new LEDLightListener();
                            LedListener.Subscribe(BuildMonitor, Settings);
                            LedListener.Start();
                        }
                        else
                        {
                            // We are running on a machine that does not support the ledlistener, so flag it as successfully started
                        }
                    }
                    catch (Exception ex)
                    {
                        Telemetry.TrackError(ex);
                        Debug.WriteLine("Could not initialise LED listener: " + ex.Message);
                    }
                }

                await Log("Starting build monitor...");

                BuildMonitor.Start(Settings, CancellationToken.Token);
            }
            else
            {
                RunButtonText = "Start";

                Telemetry.TrackEvent("App.StopClick");
                if (LedListener != null)
                {
                    LedListener.Dispose();
                    LedListener.Unsubscribe(BuildMonitor);
                    LedListener = null;
                }
                CancellationToken.Cancel();
            }
        }
Esempio n. 14
0
        public override void Dispose()
        {
            CancellationToken?.Cancel();

            Stream?.Dispose();

#if DEBUG
            PacketsReceived?.Clear();
            PacketsSended?.Clear();
#endif

            CancellationToken?.Dispose();
        }
Esempio n. 15
0
                static IEnumerable <TSource> BatchByBulker(IEnumerator <TSource> e, int count, CancellationToken token)
                {
                    for (var x = 0u; x < count; x++)
                    {
                        yield return(e.Current);

                        if (!e.MoveNext())
                        {
                            token.Cancel();
                            yield break;
                        }
                    }
                }
Esempio n. 16
0
        public async Task StopServiceAsync()
        {
            _isActiveService = false;
            if (_thread != null)
            {
                CancellationToken.Cancel();
                await Task.WhenAll(ThreadCompletion.Task);

                _thread           = null;
                ThreadCompletion  = null;
                CancellationToken = null;
            }
        }
Esempio n. 17
0
 public IEngine Stop()
 {
     return(this.Fluently(() => {
         // Wait for any active tasks, perform appropriate actions to ensure no loss
         this.GuardedExecution(() => {
             this.GuardedExecutionAsync(async() => {
                 CancellationToken.Cancel();
                 await ProcessorTask;
             });
             Logger.LogIfNot(Processor.Dehydrate, LogLevel.Error);
         });
     }));
 }
Esempio n. 18
0
        public override void Disconnect()
        {
            foreach (KeyValuePair <ProductUserId, Client> client in _connectedEpicUsers)
            {
                client.Value.Disconnect();
                _connectedEpicUsers.Remove(client);
            }

            ProcessIncomingMessages();

            CancellationToken.Cancel();

            Dispose();
        }
Esempio n. 19
0
        public override void OpenUserInterfaceElement(string rawDeviceList)
        {
            _parsedListCache = ParseDeviceList(rawDeviceList);

            _credToken = CredentialManager.RequestCredentials();

            if (_credToken == null)
            {
                var msg = $"Action {ActionName} canceled by user.";
                Logger.LogMessage(msg);
                ResultConsole.AddConsoleLine(msg);
                CancellationToken.Cancel();
            }
        }
        private async void End()
        {
            IsEnabledEnd   = false;
            IsEnabledStart = true;
            CancellationToken.Cancel();
            await Task.Delay(2000);

            var urlAPI         = Application.Current.Resources["URLAPI"].ToString();
            var mainViewModel  = MainViewModel.GetInstance();
            var responseDelete = await apiService.Delete(
                urlAPI,
                "/locations",
                mainViewModel.Driver.Token,
                key);
        }
Esempio n. 21
0
        /// <summary>
        /// Cancels the queue from processing
        /// </summary>
        /// <param name="wait">
        /// Determines if the function should wait for the tasks to complete before returning
        /// </param>
        /// <returns>True if it is cancelled, false otherwise</returns>
        public bool Cancel(bool wait = false)
        {
            if (IsCompleted || IsCanceled)
            {
                return(true);
            }

            CancellationToken?.Cancel(false);
            if (wait)
            {
                Task.WaitAll(Tasks);
            }

            return(true);
        }
        /// <summary>
        /// Отменяет запрос, если это возможно
        /// </summary>
        public void Cancel()
        {
            if (!CanBeCanceled)
            {
                return;
            }

            if (CancellationToken != null)
            {
                CancellationToken.Cancel();
            }
            else
            {
                Complete(RequestCompletionResult.Canceled);
            }
        }
        public void Cancel()
        {
            ImageService.Instance.RemovePendingTask(this);

            if (!_isDisposed)
            {
                try
                {
                    CancellationToken?.Cancel();
                }
                catch (ObjectDisposedException)
                {
                }
            }
            Finish();
            Logger.Debug(string.Format("Canceled image generation for {0}", GetKey()));
        }
Esempio n. 24
0
        public void Stop()
        {
            if (CancellationToken.IsCancellationRequested)
            {
                return;
            }
            CancellationToken.Cancel();

            if (SocketConnected(Socket))
            {
                //TODO
                Disconnected(true);
            }
            else
            {
                Disconnected(false);
            }
        }
Esempio n. 25
0
        public override void Show()
        {
            base.Show();

            var window = ViewService.Instance.TryGet <Window>(this);

            if (window != null)
            {
                window.Closing += (o, a) =>
                {
                    CancellationToken.Cancel();
                    this.Dispose();
                };
                timer.Change(0, Period);
                ProgressState  = ProgressState.Error;
                window.Topmost = true;
                window.Show();
            }
        }
Esempio n. 26
0
        static int Main(string[] args)
        {
            Console.CancelKeyPress += (s, e) => {
                e.Cancel = true;
                _cancellationToken.Cancel();
            };

            try {
                Action action = _commands.Parse(args);
                if (action != null)
                {
                    action();

                    Console.WriteLine();
                    if (_cancellationToken.IsCancelled)
                    {
                        Console.WriteLine("Cancelled.");
                    }
                    else
                    {
                        Console.WriteLine("Done.");
                    }
                    return(0);
                }
                else
                {
                    Console.Error.WriteLine();
                    Console.Error.WriteLine("Unknown Command. Use --help for more information.");
                }
            }
            catch (AggregateException ex) {
                Console.Error.WriteLine();
                ex.Handle(x => {
                    Console.Error.WriteLine(x.Message);
                    return(true);
                });
            }
            catch (Exception e) {
                Console.Error.WriteLine();
                Console.Error.WriteLine(e.Message);
            }
            return(1);
        }
Esempio n. 27
0
        /// <inheritdoc />
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            try
            {
                //Graphics?.Dispose();
                BlockLightCalculations?.Dispose();
                BlockLightCalculations = null;

                SkyLightCalculator?.Dispose();
                SkyLightCalculator = null;

                _renderSampler.Dispose();
                CancellationToken.Cancel();
                UpdateQueue.Clear();
                FastUpdateQueue.Clear();
                UpdateBorderQueue.Clear();

                foreach (var chunk in Chunks)
                {
                    chunk.Value.Dispose();
                }

                Chunks.Clear();

                foreach (var rendered in _renderedChunks)
                {
                    rendered.Dispose();
                }

                _renderedChunks = null;
            }
            finally
            {
                _disposed = true;
            }
        }
Esempio n. 28
0
        /// <inheritdoc />
        public void Dispose()
        {
            //Graphics?.Dispose();
            CancellationToken.Cancel();
            UpdateQueue.Clear();
            FastUpdateQueue.Clear();
            UpdateBorderQueue.Clear();

            foreach (var chunk in Chunks)
            {
                chunk.Value.Dispose();
            }

            Chunks.Clear();

            foreach (var rendered in _renderedChunks)
            {
                rendered.Dispose();
            }

            _renderedChunks = null;
        }
Esempio n. 29
0
        public void TestCancellation()
        {
            var v1 = new Operands(3, 5);
            var v2 = new Operands(7, 2);

            Assert.AreEqual(0, v1.result);
            Assert.AreEqual(0, v2.result);

            var token     = new CancellationToken();
            var scheduler = new Scheduler(0f, 20);

            scheduler.Invoke(ComputeProduct, 3, this, v1, token);
            scheduler.Invoke(ComputeProduct, 5, this, v2, token);
            Assert.AreEqual(2, scheduler.QueueLength);
            Assert.AreEqual(0, v1.result);
            Assert.AreEqual(0, v2.result);

            token.Cancel();
            scheduler.Update(6f);
            Assert.AreEqual(0, scheduler.QueueLength);
            Assert.AreEqual(0, v1.result);
            Assert.AreEqual(0, v2.result);
        }
Esempio n. 30
0
        public override void OpenUserInterfaceElement(string rawDeviceList)
        {
            _parsedListCache = ParseDeviceList(rawDeviceList);

            var sccmRegHackContext = new SccmRegHackOptionViewModel();

            _windowService.ShowDialog <SccmRegHackOptionsPrompt>(sccmRegHackContext);

            if (!sccmRegHackContext.Result)
            {
                var msg = $"Action {ActionName} canceled by user.";
                Logger.LogMessage(msg);
                ResultConsole.AddConsoleLine(msg);
                CancellationToken.Cancel();
            }

            _remoteAccessEnabled     = sccmRegHackContext.RemoteAccessEnabled;
            _requiresUserApproval    = sccmRegHackContext.RequiresUserApproval;
            _showConnectionBanner    = sccmRegHackContext.ShowConnectionBanner;
            _showTaskBarIcon         = sccmRegHackContext.ShowTaskbarIcon;
            _allowAccessOnUnattended = sccmRegHackContext.AllowAccessOnUnattended;
            _allowLocalAdministratorsToRemoteControl = sccmRegHackContext.AllowLocalAdministratorsToRemoteControl;
        }