private void btnCancel_Click(object sender, RoutedEventArgs e) { CancelTokenSource.Cancel(); Log("Cancelling..."); Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; }
private void StartInputProcessingThread() { try { CancelTokenSource?.Cancel(); CancelTokenSource?.Dispose(); } catch { } // After BlockInput is enabled, only simulated input coming from the same thread // will work. So we have to start a new thread that runs continuously and // processes a queue of input events. _inputProcessingThread = new Thread(() => { Logger.Write($"New input processing thread started on thread {Thread.CurrentThread.ManagedThreadId}."); CancelTokenSource = new CancellationTokenSource(); if (_inputBlocked) { ToggleBlockInput(true); } CheckQueue(CancelTokenSource.Token); }); _inputProcessingThread.SetApartmentState(ApartmentState.STA); _inputProcessingThread.Start(); }
private void StartInputActionTask() { CancelTokenSource?.Cancel(); CancelTokenSource = new CancellationTokenSource(); CancelToken = CancelTokenSource.Token; InputActionsTask = Task.Run(CheckQueue, CancelTokenSource.Token); }
/// <summary> /// Deinit driver communiation - means autorefresh of the messages /// </summary> /// <returns></returns> public override async Task DeInit() { if (CancelToken != null) { CancelTokenSource.Cancel(); } }
/// <summary> /// Removes the item from the queue. If the item is currently being processed, the task /// is cancelled. /// </summary> /// <param name="mediaQueueId">The media queue ID.</param> public void RemoveMediaQueueItem(int mediaQueueId) { MediaQueueItem item; if (MediaQueueItemDictionary.TryGetValue(mediaQueueId, out item)) { MediaQueueItem currentItem = GetCurrentMediaQueueItem(); if ((currentItem != null) && (currentItem.MediaQueueId == mediaQueueId)) { CancelTokenSource.Cancel(); if (Task != null) { Task.Wait(20000); // Wait up to 20 seconds } Instance.Status = MediaQueueStatus.Idle; } //Factory.GetDataProvider().MediaQueue_Delete(item); item.Delete(); MediaQueueItemDictionary.TryRemove(mediaQueueId, out item); } }
public override void Stop(bool waitForQueueToDrain) { stopping = true; //See if we want to wait for the queue to drain before stopping if (waitForQueueToDrain) { while (QueuedNotificationCount > 0 || sentNotifications.Count > 0) { Thread.Sleep(50); } } //Sleep a bit to prevent any race conditions //especially since our cleanup method may need 3 seconds Thread.Sleep(5000); if (!CancelTokenSource.IsCancellationRequested) { CancelTokenSource.Cancel(); } //Wait on our tasks for a maximum of 30 seconds Task.WaitAll(new Task[] { base.taskSender, taskCleanup }, 30000); }
} // end of function - StartReader /*======================= PROTECTED =====================================*/ /************************ Events *****************************************/ /************************ Properties *************************************/ /************************ Construction ***********************************/ /************************ Methods ****************************************/ /// <summary> /// Explicit dispose method /// </summary> /// <param name="disposing"> /// Are we explicitly disposing, or called from the destructor /// </param> protected virtual void Dispose(bool disposing) { if (!CancelTokenSource.IsCancellationRequested) { CancelTokenSource.Cancel(); } // end of if - cancel has not already be requested try { #warning Should revisit this wait on the data reader DataReader.Wait(4000); } catch (Exception) { // Nothing to do with this exception at this point } if (disposing) { if (CloseStream && null != BaseStream) { BaseStream.Close(); BaseStream.Dispose(); } // end of if - we should close the base stream CancelTokenSource.Dispose(); } // end of if - explicitly disposing BaseStream = null; CancelTokenSource = null; } // end of function - Dispose
public bool WriteTxt(string txtPath, string searchTxt, string path) { if (Token.IsCancellationRequested) { return(false); } var fileName = Path.GetFileName(path); if (fileName != null && fileName.Equals(searchTxt)) { using (var tw = new StreamWriter(txtPath, true)) { tw.WriteLine(Environment.NewLine + "Gefunden: " + path); // Global Variable begin FoundTargetPath = path; tw.WriteLine(Environment.NewLine + "Text :" + ReadTxt()); // Global Variable end CancelTokenSource.Cancel(); return(true); } } using (var tw = new StreamWriter(txtPath, true)) { tw.WriteLine(path); return(false); } }
public override void Stop(bool waitForQueueToDrain) { stopping = true; //See if we want to wait for the queue to drain before stopping if (waitForQueueToDrain) { var sentNotificationCount = 0; lock (sentLock) sentNotificationCount = sentNotifications.Count; while (QueuedNotificationCount > 0 || sentNotificationCount > 0 || Interlocked.Read(ref trackedNotificationCount) > 0) { Thread.Sleep(100); lock (sentLock) sentNotificationCount = sentNotifications.Count; } } if (!CancelTokenSource.IsCancellationRequested) { CancelTokenSource.Cancel(); } //Wait on our tasks for a maximum of 5 seconds Task.WaitAll(new Task[] { base.taskSender, taskCleanup }, 5000); }
/// <inheritdoc /> public Task StopHandlingNetworkClient() { isNetworkHandling = false; CancelTokenSource.Cancel(); //TODO: Should we await for the dispatch thread to actually end?? return(Task.CompletedTask); }
public virtual void StopTask() { if (!TaskRunning) { return; } CancelTokenSource?.Cancel(); Wait?.Set(); }
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { e.Cancel = true; foreach (var shard in Shards) { shard.StopAsync().GetAwaiter().GetResult(); // it dun matter } CancelTokenSource.Cancel(); }
/// <summary> /// Creates a new webmedia client with the given IP, Port, and HTTP server /// </summary> /// <param name="ip">The IP of the webmedia link server</param> /// <param name="port">The port of the webmedia link server</param> /// <param name="httpIp">The IP to host the HTTP server from</param> /// <param name="httpPort">The port to host the HTTP server on</param> /// <param name="name">The name of the media server</param> /// <param name="password">The password of the media server</param> /// <param name="pathToMediaFiles">The location of the folder containing the media files</param> /// <param name="pathToDownloadFiles">The location of the folder containing the download files</param> /// <param name="pathToSubtitleFiles">The location of the folder containing the subtitle files</param> public WebMediaClient(string ip, ushort port, string httpIp, ushort httpPort, string name, string password, string pathToMediaFiles, string pathToDownloadFiles, string pathToSubtitleFiles) { WebserverIp = ip; WebserverPort = port; MediaserverIp = httpIp; MediaserverPort = httpPort; Name = name; Password = password; MediaFilesPath = pathToMediaFiles; DownloadFilesPath = pathToDownloadFiles; SubtitleFilesPath = pathToSubtitleFiles; //Use the .exe if windows, use the . nothing otherwise if (Environment.OSVersion.Platform == PlatformID.Win32NT) { Downloader = new YoutubeDL(Helpful.GetExecutingDirectory() + "\\youtubedl.exe", CancelToken); } else { Downloader = new YoutubeDL(Helpful.GetExecutingDirectory() + "\\youtubedl", CancelToken); } //Create the media server MediaServer = new HttpServer(httpIp, httpPort, pathToMediaFiles, pathToDownloadFiles, pathToSubtitleFiles, CancelTokenSource.Token); //Populate the media server's list of available files RescanForFiles(); //Try to start media server. If it fails, stop the program if (!MediaServer.StartServer()) { CancelTokenSource.Cancel(); ConLog.Log("HTTP Server", "Failed to start HTTP server. Try running as an administrator, and check that your firewall or antivirus isn't preventing this program from starting the HTTP server", LogType.Fatal); } //Register file system watchers FileSystemWatcher mediaWatcher = new FileSystemWatcher(pathToMediaFiles, "*.*"); mediaWatcher.EnableRaisingEvents = true; mediaWatcher.IncludeSubdirectories = false; mediaWatcher.Changed += (sender, e) => UpdateAvailableFiles(); mediaWatcher.Created += (sender, e) => UpdateAvailableFiles(); mediaWatcher.Deleted += (sender, e) => UpdateAvailableFiles(); mediaWatcher.Renamed += (sender, e) => UpdateAvailableFiles(); FileSystemWatcher downloadWatcher = new FileSystemWatcher(pathToDownloadFiles, "*.*"); downloadWatcher.EnableRaisingEvents = true; downloadWatcher.IncludeSubdirectories = false; downloadWatcher.Changed += (sender, e) => UpdateAvailableFiles(); downloadWatcher.Created += (sender, e) => UpdateAvailableFiles(); downloadWatcher.Deleted += (sender, e) => UpdateAvailableFiles(); downloadWatcher.Renamed += (sender, e) => UpdateAvailableFiles(); }
/// <summary> /// Stop the data processor async task /// </summary> public async Task StopRealTimeProcessingAsyncAsync() { if (CancelTokenSource != null) { CancelTokenSource.Cancel(); await MonitorRunTask; CancelTokenSource = null; MonitorRunTask = null; Log?.Invoke(this, new LogEventArgs(Name, this, "StopMonitorAsync", $"Stopped signal filtering for {Name}.", LogLevel.INFO)); } }
/// <summary> /// Stop the data processor async task /// </summary> public async Task StopDetectorAsync() { if (CancelTokenSource != null) { CancelTokenSource.Cancel(); await RunTask; CancelTokenSource = null; RunTask = null; } Log?.Invoke(this, new LogEventArgs(this, "StopDetectorAsync", $"Stopped alpha wave detector.", LogLevel.INFO)); }
/// <summary> /// Stop the data processor async task /// </summary> public async Task StopMonitorAsync() { if (CancelTokenSource != null) { CancelTokenSource.Cancel(); await MonitorRunTask; CancelTokenSource = null; MonitorRunTask = null; Log?.Invoke(this, new LogEventArgs(Name, this, "StopMonitorAsync", $"Stopped band power monitor for {Name}.", LogLevel.INFO)); } }
/// <summary> /// Stop status monitor /// </summary> public async Task StopStatusMonitorAsync() { if (CancelTokenSource != null) { CancelTokenSource.Cancel(); if (RunTask != null) { await RunTask; } CancelTokenSource = null; RunTask = null; } }
/// <summary> /// Stop data broadcast server /// </summary> public async Task StopDataBroadcastServerAsync() { if (CancelTokenSource != null) { CancelTokenSource.Cancel(); if (RunTask != null) { await RunTask; } CancelTokenSource = null; RunTask = null; } }
public Task <bool> RunAsConsole() { Console.WriteLine("Making chat-sender..."); while (!CancelTokenSource.Token.IsCancellationRequested) { var message = Console.ReadLine(); SendMessage(message); if (message == "!quit" || message == "!exit") { CancelTokenSource.Cancel(); } } return(Task.FromResult(true)); }
protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { CancelTokenSource?.Cancel(); ComparerTask?.Wait(); CancelTokenSource?.Dispose(); ComparerTask?.Dispose(); LeftVideoFile?.Dispose(); RightVideoFile?.Dispose(); } disposedValue = true; } }
/// <summary> /// Stop the broadcaster and close the outlet /// </summary> /// <returns></returns> public async Task StopLslBroadcastAsync() { if (CancelTokenSource != null) { CancelTokenSource.Cancel(); if (RunTask != null) { await RunTask; } CancelTokenSource = null; RunTask = null; } DataToBroadcast.RemoveAll(); }
/// <summary> /// Stop the board reader process /// </summary> public async Task StopBoardDataReaderAsync() { if (CancelTokenSource != null) { Log?.Invoke(this, new LogEventArgs(this, "StopBoardDataReaderAsync", $"Stopping board data reader", LogLevel.DEBUG)); CancelTokenSource.Cancel(); if (RunTask != null) { await RunTask; } CancelTokenSource = null; RunTask = null; await ReleaseBoardAsync(); } }
private void StartInputProcessingThread() { CancelTokenSource?.Cancel(); CancelTokenSource?.Dispose(); var newThread = new Thread(() => { Logger.Write($"New input processing thread started on thread {Thread.CurrentThread.ManagedThreadId}."); CancelTokenSource = new CancellationTokenSource(); if (inputBlocked) { ToggleBlockInput(true); } CheckQueue(CancelTokenSource.Token); }); newThread.SetApartmentState(ApartmentState.STA); newThread.Start(); }
public void ToggleBlockInput(bool toggleOn) { InputActions.Enqueue(() => { _inputBlocked = toggleOn; var result = BlockInput(toggleOn); Logger.Write($"Result of ToggleBlockInput set to {toggleOn}: {result}"); if (!toggleOn) { CancelTokenSource.Cancel(); } }); if (toggleOn) { StartInputProcessingThread(); } }
public CannotCloseDialogViewModel() : base("", false, false) { Global = Locator.Current.GetService <Global>(); OperationMessage = "Dequeuing coins...Please wait"; var canCancel = this.WhenAnyValue(x => x.IsBusy); var canOk = this.WhenAnyValue(x => x.IsBusy, (isbusy) => !isbusy); OKCommand = ReactiveCommand.CreateFromTask( async() => { CancelTokenSource.Cancel(); while (!Initialization.IsCompleted) { await Task.Delay(300); } // OK pressed. Close(false); }, canOk); CancelCommand = ReactiveCommand.CreateFromTask( async() => { OperationMessage = "Cancelling...Please wait"; CancelTokenSource.Cancel(); while (!Initialization.IsCompleted) { await Task.Delay(300); } // OK pressed. Close(false); }, canCancel); Observable .Merge(OKCommand.ThrownExceptions) .Merge(CancelCommand.ThrownExceptions) .ObserveOn(RxApp.TaskpoolScheduler) .Subscribe(ex => Logger.LogError(ex)); }
public string SendMessage(string msg) { var formattedTimeString = DateTime.Now.ToString("HH':'mm':'ss"); try { Chat.K++; ChatSpace.Put(Chat.K, formattedTimeString, LoggedInUser, msg); } catch (SocketException ex) { Console.WriteLine(ex.Message); CancelTokenSource.Cancel(); return(string.Empty); } catch (Exception ex) { Console.WriteLine(ex); } return(FormatMessage(LoggedInUser, msg)); }
/// <summary> /// Stop the data processor async task, and all component processor tasks /// </summary> public async Task StopDataProcessorAsync(bool flush = false) { FlushQueue = flush; if (CancelTokenSource != null) { await StopRealTimeSignalProcessingAsync(); await BandPowers.StopMonitorAsync(); CancelTokenSource.Cancel(); await Task.WhenAll(RawDataQueueProcessorTask, DataMonitorTask, PeriodicProcessorTask); CancelTokenSource = null; RawDataQueueProcessorTask = null; PeriodicProcessorTask = null; DataMonitorTask = null; Log?.Invoke(this, new LogEventArgs(Name, this, "StopDataProcessor", $"Stopped Brainflow data processor for {Name}.", LogLevel.INFO)); } }
/// <summary> /// Removes the item from the queue. If the item is currently being processed, the task /// is cancelled. /// </summary> /// <param name="mediaQueueId">The media queue ID.</param> public void RemoveMediaQueueItem(int mediaQueueId) { MediaQueueDto item; if (MediaQueueItemDictionary.TryGetValue(mediaQueueId, out item)) { MediaQueueDto currentItem = GetCurrentMediaQueueItem(); if ((currentItem != null) && (currentItem.MediaQueueId == mediaQueueId)) { CancelTokenSource.Cancel(); if (Task != null) { Task.Wait(); } } Factory.GetDataProvider().MediaQueue_Delete(item); MediaQueueItemDictionary.TryRemove(mediaQueueId, out item); } }
protected override async void LoadAsync() { CancelTokenSource?.Cancel(); CancellationTokenSource newCts = new CancellationTokenSource(); CancelTokenSource = newCts; try { SqlRevaluationProductRepository repository = new SqlRevaluationProductRepository(); ReportsList = new ObservableCollection <RevaluationProduct>(await repository.GetReportRevaluation( CancelTokenSource.Token)); } catch (OperationCanceledException) { } catch (Exception e) { MessageBox.Show(e.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } if (CancelTokenSource == newCts) { CancelTokenSource = null; } }
public void Cancel(bool force = false) { if (force) { CancelTokenSource.Cancel(); } else { if (TaskStarted) { CancelTokenSource.Cancel(); } else { ShouldCancel = true; } } if (Connection != null) { Connection.Stop(); } }