private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { mainUITimer.Stop(); UpdateUi(); go_button.Enabled = true; cancel_button.Enabled = false; threads_numericUpDown.Enabled = true; iterations_numericUpDown.Enabled = true; queryDelay_textBox.Enabled = true; if (!_cancelled) { progressBar1.Value = 100; } ((BackgroundWorker)sender).Dispose(); _backgroundWorkerCTS?.Dispose(); db_label.Text = string.Empty; activeThreads_textBox.Text = "0"; if (!string.IsNullOrEmpty(_runParameters.ResultsAutoSaveFileName)) { AutoSaveResults(_runParameters.ResultsAutoSaveFileName); } // if we started automatically exit when done if (_exitOnComplete || _runParameters.Unattended) { Dispose(); } }
public void PauseSpeaking() { if (enabled) { paused = true; tokenSource.Cancel(); tokenSource.Dispose(); tokenSource = new System.Threading.CancellationTokenSource(); } }
// Runs `action`. If called multiple times, actions are called in strict sequential order. // If a previously enqueued action has not started running, it will never be called. // (In other words, new actions render older ones obsolete.) public void EnqueueEvent(System.Action action) { LastCancellationTokenSource.Cancel(); LastCancellationTokenSource.Dispose(); LastTask = LastTask.ContinueWith( (System.Threading.Tasks.Task previousTask) => { action(); }, (LastCancellationTokenSource = new System.Threading.CancellationTokenSource()).Token, System.Threading.Tasks.TaskContinuationOptions.LazyCancellation, System.Threading.Tasks.TaskScheduler.Current ); }
public void StartProgram(OvenProgram op) { if (_cts != null) { _cts.Dispose(); } _cts = new System.Threading.CancellationTokenSource(); Task.Run(() => ProgramLoop(op, _cts.Token)); }
private async void button3_Click(object sender, EventArgs e) { if (_isSearching) { return; } try { _isSearching = true; _token = new System.Threading.CancellationTokenSource(); dataGridView1.DataSource = await Task.Run(() => mlRepository.GetML(_token.Token), _token.Token); MessageBox.Show("完了"); } catch (OperationCanceledException o) { MessageBox.Show("キャンセル"); } finally { _token.Dispose(); _token = null; _isSearching = false; } }
async void Run() { if (ga != null && ga.IsRunning) { return; } Cursor = Cursors.Wait; scoreHistory = new List <Tuple <double, double, double> >(); ShowScorePlot(); ga = new AutoGA(targetFile, int.Parse(poolSize.Text)); canceller = new System.Threading.CancellationTokenSource(); ga.Cancell = canceller.Token; ga.OnUpdate = Update; ga.Initial = initialTree; var gen = int.Parse(maxGeneration.Text); stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); await Task.Run(() => { ga.Init(); ga.Run(gen); }, canceller.Token); stopwatch.Stop(); canceller.Dispose(); canceller = null; ga.SaveResult(System.IO.Path.ChangeExtension(targetFile, GAResult.Extension)); //ga.BestElite.Tree.Serialize(System.IO.Path.ChangeExtension(targetFile, "bin")); generation.Content = "complete"; Cursor = null; MainWindow.Instance.SetInitial(ga.BestElite.Tree); }
public static void Stop(string name = "") { try { cancellationToken?.Cancel(); cancellationToken?.Dispose(); cancellationToken = null; if (!string.IsNullOrEmpty(name)) { var n = name.LastIndexOf("."); name = name.Substring(0, n) + "_cmd.ini"; if (File.Exists(name)) { var lines = File.ReadAllLines(name).Where(l => l.StartsWith("stop", StringComparison.OrdinalIgnoreCase)).ToArray(); if (lines.Length > 0) { Task.Run(() => { foreach (var item in lines) { Send(item.Substring(5)); Task.Delay(100).Wait(); } }); } } } } catch { } }
public void Run(IBackgroundTaskInstance taskInstance) { // Check the task cost var cost = BackgroundWorkCost.CurrentBackgroundWorkCost; if (cost == BackgroundWorkCostValue.High) { return; } // Get the cancel token var cancel = new System.Threading.CancellationTokenSource(); taskInstance.Canceled += (s, e) => { cancel.Cancel(); cancel.Dispose(); }; // Get deferral var deferral = taskInstance.GetDeferral(); try { // Update Tile with the new xml XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(TileUpdaterTask.w10TileXml); TileNotification tileNotification = new TileNotification(xmldoc); TileUpdater tileUpdator = TileUpdateManager.CreateTileUpdaterForApplication(); tileUpdator.Update(tileNotification); } finally { deferral.Complete(); } }
private async void Button1ClickExe() { // 普通に同期的な記述で OK // メソッドに async // 処理を Task で,await させる try { // キャンセルトークンの設定 // 非同期処理開始時に new する _token = new System.Threading.CancellationTokenSource(); // 非同期処理メソッドにキャンセルトークン .Token を渡し,監視するようにする // Task にも渡せるので,渡しておく DataGridSource = await Task.Run(() => _dataBase.GetData(_token.Token), _token.Token); MessageBox.Show("完了"); } catch (OperationCanceledException o) { MessageBox.Show("キャンセルされました"); } finally { _token.Dispose(); _token = null; } }
//「async」が必要 private async void button1_Click(object sender, EventArgs e) { _token = new System.Threading.CancellationTokenSource(); /*await syncを組み合わせた例 * より同期プログラミングと似たような記述ができる * GetDataが終了するまで messageBoxの処理を待つ */ //_isCancel = false; try { //第二引数にもトークンを渡すとキャンセル時にすぐに止まる dataGridView1.DataSource = await Task.Run(() => _dataBase.GetData(_token.Token), _token.Token); MessageBox.Show("完了"); } catch (OperationCanceledException) { MessageBox.Show("キャンセルされました。"); } finally { _token.Dispose(); _token = null; } //if (_dataBase.IsCancel) //{ // MessageBox.Show("キャンセルされました。"); //}else //{ // MessageBox.Show("完了"); //} }
public void Dispose() { if (cancelationToken != null) { cancelationToken.Dispose(); } }
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { ctSource_.Cancel(); ctSource_.Dispose(); autoruns_.Dispose(); }
public void UC07_DataflowReceiveAny() { // Create a shared CancellationTokenSource object to enable the // TrySolution method to be cancelled. var cts = new System.Threading.CancellationTokenSource(); DataflowReceiveAny dataflowReceiveAny = new DataflowReceiveAny(); // Create three TransformBlock<int, int> objects. // Each TransformBlock<int, int> object calls the TrySolution method. Func <int, int> transform = n => dataflowReceiveAny.TrySolution(n, cts.Token); var trySolution1 = new TransformBlock <int, int>(transform); var trySolution2 = new TransformBlock <int, int>(transform); var trySolution3 = new TransformBlock <int, int>(transform); // Post data to each TransformBlock<int, int> object. trySolution1.Post(11); trySolution2.Post(21); trySolution3.Post(31); // Call the ReceiveFromAny<T> method to receive the result from the // first TransformBlock<int, int> object to finish. int result = dataflowReceiveAny.ReceiveFromAny(trySolution1, trySolution2, trySolution3); // Cancel all calls to TrySolution that are still active. cts.Cancel(); // Print the result to the console. Console.WriteLine("The solution is {0}.", result); cts.Dispose(); }
public void StartSessions() { if (m_CancelSource != null) { m_CancelSource.Dispose(); m_CancelSource = null; } m_CancelSource = new System.Threading.CancellationTokenSource(); }
private void _TaskFinally(object result) { _Result = result; _CancelSource.Dispose(); _CancelSource = null; this.Dispatcher.Invoke(this.Close); }
public void StartSessions(SearchContext context) { if (m_CancelSource != null) { m_CancelSource.Dispose(); m_CancelSource = null; } m_CancelSource = new System.Threading.CancellationTokenSource(); currentSessionContext = new SearchSessionContext(context); }
/// <summary> /// The BackgroundWorker Function responsible for Brute Forcing the cipher. This is the 'Bread and Butter' of the app /// </summary> private void BruteForceWorker_DoWork(object sender, DoWorkEventArgs e) { //Alphabet to start with when Brute Forcing string Alpha = new string(new[] { 'Z', 'O', 'M', 'B', 'I', 'E', 'F', 'G', 'H', 'K', 'L', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'A', 'C', 'D' }); //Set Max CPU usage var opts = new ParallelOptions(); if (CPUperc == "LOW") { opts.MaxDegreeOfParallelism = 4; } //Set Cancel Token for Brute Force Thread opts.CancellationToken = cts.Token; //Load Ngrams GenericScoring.ngram_score.LoadNgarmDoubleFile(Properties.Resources.english_trigrams, Properties.Resources.english_quadgrams); //Start the Brute Forcing Loop try { Parallel.ForEach(Infinite(), opts, new Action <bool>((val) => { opts.CancellationToken.ThrowIfCancellationRequested(); //Shuffle the Alphabet and get a random Cipher Key string C_Aplha = Alpha.Shuffle(); //Decipher the ciphertext by Substitution var ret = Cipher.Substitute(C_Aplha); //------var ret = SubstitutionSolve(Cipher, C_Aplha);---// //Get Score of the return by calculating the English Ngram Frequencies in it var Sscore = GenericScoring.ngram_score.ScoreDouble(ret); //If the Score in above -120 (Average English Ngram Score for a 34 length Sentence), send to server if (Sscore > -280) { GoodCount++; //FIND A BETTER WAY TO HANDLE THIS HTTP EXCEPTION SO WE DO NOT LOSE THIS DATA!! try{ client.SetData(ret, C_Aplha, Convert.ToInt32(Sscore), ContributerName); }catch (Exception) {} } //Log best score so far for UI log if (Sscore > BestScore) { BestScore = Sscore; GlobalUpdateString = "Your Best Score So Far: " + Environment.NewLine + "Key: " + C_Aplha + Environment.NewLine + "Result: " + ret + Environment.NewLine + "Score: " + Sscore; } TotalCount++; })); }//Catch when user cancels the process by hitting the stop button. catch (OperationCanceledException ex) { } finally { cts.Dispose(); } }
public void Dispose() { if (_mainCancelSource == null) { return; } _mainCancelSource.Cancel(); _mainCancelSource.Dispose(); ClearChannel(); ClearConnection(); _mainCancelSource = null; }
public static void DoSample() { var cancellationTokenSource = new System.Threading.CancellationTokenSource(); var task = System.Threading.Tasks.Task.Factory.StartNew <int>(() => Count(cancellationTokenSource.Token)); Console.WriteLine("Press [Enter] to stop counting."); Console.ReadLine(); cancellationTokenSource.Dispose(); Console.WriteLine("Counting stopped at {0}", task.GetAwaiter().GetResult()); Console.ReadLine(); }
static StackObject *Dispose_2(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Threading.CancellationTokenSource instance_of_this_method = (System.Threading.CancellationTokenSource) typeof(System.Threading.CancellationTokenSource).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.Dispose(); return(__ret); }
/// <summary> /// Clears all async search sessions held by this MultiProviderAsyncSearchSession. /// </summary> public void Clear() { m_CancelSource?.Dispose(); m_CancelSource = null; foreach (var searchSession in m_SearchSessions) { searchSession.Value.asyncItemReceived -= OnProviderAsyncItemReceived; searchSession.Value.sessionStarted -= OnProviderAsyncSessionStarted; searchSession.Value.sessionEnded -= OnProviderAsyncSessionEnded; } m_SearchSessions.Clear(); asyncItemReceived = null; }
public void Hide() { if (_dialog != null) { _dialog.CancelEvent -= Dialog_CancelEvent; _dialog.Dismiss(); _dialog.Dispose(); _dialog = null; if (_cancellaction != null) { _cancellaction.Dispose(); _cancellaction = null; } } }
public System.Threading.CancellationToken ShowWithCancel() { if (_cancellaction == null) { _cancellaction = new System.Threading.CancellationTokenSource(); Show(() => { _cancellaction.Cancel(); _cancellaction.Dispose(); _cancellaction = null; }); return(_cancellaction.Token); } return(default(System.Threading.CancellationToken)); }
protected override void Dispose(bool disposing) { base.Dispose(disposing); if (ShouldDispose) { m_ResetEvent.Dispose(); //m_ResetEvent = null; m_TokenSource.Dispose(); //m_TokenSource = null; } }
protected virtual void OnStop() { if (_mainCancelToken != null) { _mainCancelToken.Cancel(); _mainCancelToken.Dispose(); return; } if (CommunicateFactory == null) { return; } CommunicateFactory.DisposeQueue(); }
/// <summary> /// 释放资源 /// </summary> public void Dispose() { if (_entityQueue != null) { _entityQueue.Dispose(); } _entityQueue = null; if (_mainToken == null) { return; } _mainToken.Cancel(); _mainToken.Dispose(); _mainToken = null; }
private async void Game_Finished(object sender, EventArgs e) { var game = (Core.Game)sender; game.Finished -= Game_Finished; game.TurnChanged -= Game_TurnChanged; tokenSource?.Dispose(); tokenSource = new System.Threading.CancellationTokenSource(); gameTask = null; await Dispatcher.BeginInvoke(new Action(() => { abortGameItem.Visibility = Visibility.Collapsed; newGameItem.Visibility = Visibility.Visible; })); }
protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { EndTaskToken.Cancel(true); TestConnectionTask.Wait(); CloseConnection(); if (EndTaskToken != null) { EndTaskToken.Dispose(); } } }
/// <summary> /// /// </summary> /// <returns></returns> private CallOptions CreateCallOptions() { if (m_CancelToken != null) { m_CancelToken.Dispose(); } m_CancelToken = new System.Threading.CancellationTokenSource(); ++m_CallCounter; Metadata headers = new Metadata(); headers.Add("CallCounter", m_CallCounter.ToString()); CallOptions options = new CallOptions(headers, null, m_CancelToken.Token); return(options); }
private async void button1_Click(object sender, EventArgs e) { try { _token = new System.Threading.CancellationTokenSource(); dataGridView1.DataSource = await Task.Run(() => database.GetData(_token.Token), _token.Token); MessageBox.Show("完了"); } catch (OperationCanceledException o) { MessageBox.Show("キャンセル"); } finally { _token.Dispose(); _token = null; } }
public void Start(Job job) { lock (_startupLock) { Stop(false); _cancellationTokenSource = new System.Threading.CancellationTokenSource(); var token = _cancellationTokenSource.Token; ActiveTask = System.Threading.Tasks.Task.Run(() => { try { job(token); } finally { lock (_innerLock) { _cancellationTokenSource?.Dispose(); _cancellationTokenSource = null; } } }, token); } }
public bool AutoRun(Slider slider, Slider timeSlider, System.Threading.Tasks.TaskScheduler scheduler) { if (autoMode == false) { autoMode = true; cancellationTokenSource = new System.Threading.CancellationTokenSource(); System.Threading.CancellationToken cancellationToken = cancellationTokenSource.Token; System.Threading.Tasks.Task.Factory.StartNew(() => { while (autoMode) { if (cancellationToken.IsCancellationRequested) { cancellationTokenSource.Dispose(); break; } System.Threading.Tasks.Task.Factory.StartNew(() => { if (slider.Maximum == slider.Value) { slider.Value = slider.Minimum; } else { slider.Value = slider.Value + 1; } // ChangeLinkNum((int)slider.Value); sleepTime = timeSlider.Value; }, cancellationToken, System.Threading.Tasks.TaskCreationOptions.AttachedToParent, scheduler); System.Threading.Thread.Sleep((int)(sleepTime * 1000)); } } ); return true; } else { autoMode = false; cancellationTokenSource.Cancel(); return false; } }
public async void PlayStation(Station s, Windows.UI.Xaml.Controls.MediaElement me, bool navigate = true) { if (s == null) return; if (!NetworkCostController.IsConnectedToInternet) //makes sure Hanasu is connected to the internet. { Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>() .ShowMessage( LocalizationManager.GetLocalizedValue("InternetConnectionHeader"), LocalizationManager.GetLocalizedValue("NoInternetConnectionMsg")); return; } if (NetworkCostController.CurrentNetworkingBehavior == NetworkingBehavior.Opt_In) //if the user is roaming and/or over the data limit, notify them { Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>() .ShowMessage( LocalizationManager.GetLocalizedValue("DataConstraintsHeader"), LocalizationManager.GetLocalizedValue("StreamingDisabled2Msg")); return; } // Reset things things are ready to be played. await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => { SetMediaElement(ref me); CurrentStation = s; CurrentStationSongData = null; CurrentStationStreamedUri = null; }); StorageFile albumFile = await GetStationAlbumFromCache(); //Grab the current station's logo from the cache. if (albumFile != null) MediaControl.AlbumArt = new Uri("ms-appdata:///local/Hanasu/" + albumFile.DisplayName); //Set the logo in the media control. MediaControl.ArtistName = CurrentStation.Title; //set the station's name MediaControl.IsPlaying = true; try { if (me.CurrentState == MediaElementState.Playing || me.CurrentState == MediaElementState.Opening || me.CurrentState == MediaElementState.Buffering) { me.Pause(); await Task.Delay(1000); me.Stop(); } Uri finalUri = new Uri(s.StreamUrl, UriKind.Absolute); if (await Hanasu.Core.Preprocessor.PreprocessorService.CheckIfPreprocessingIsNeeded(finalUri, s.PreprocessorFormat)) finalUri = await Hanasu.Core.Preprocessor.PreprocessorService.GetProcessor(finalUri, s.PreprocessorFormat).Process(finalUri); CurrentStationStreamedUri = finalUri; //if (CurrentStation.ServerType.ToLower() == "shoutcast") //{ // var str = await ShoutcastService.GetShoutcastStream(finalUri); // mediaElement.SetSource(str, str.Content_Type); // mediaElement.Play(); //} //else //{ //finalUri = new Uri(finalUri.ToString() + ";stream.nsv", UriKind.Absolute); try { System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource(); var openTask = mediaElement.OpenAsync(finalUri, cts.Token); var timeoutTask = Task.Delay(10000); //Wait for a connection for 10 seconds. var successful = await Task.WhenAny(openTask, timeoutTask); if (successful == timeoutTask) { //timeout. inform the user and back out. IsPlaying = false; Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>() .ShowMessage( LocalizationManager.GetLocalizedValue("StreamingErrorHeader"), LocalizationManager.GetLocalizedValue("StreamingConnectionTimeoutMsg")); cts.Cancel(); cts.Dispose(); ResetStationInfo(); return; } } catch (Exception ex) { if (ex is TaskCanceledException) return; throw ex; } if (navigate && IsPlaying) NavigateToNowPlayingPage(finalUri); try { if (!PlayToController.IsConnectedViaPlayTo) { var playTask = mediaElement.PlayAsync(System.Threading.CancellationToken.None); IsPlaying = true; await playTask; } else IsPlaying = true; } catch (Exception ex) { if (ex is TaskCanceledException) return; throw ex; } //} } catch (Exception ex) { if (mediaElement.CurrentState == MediaElementState.Playing || mediaElement.CurrentState == MediaElementState.Opening) return; //Ignorable error. Probably nothing. IsPlaying = false; Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>() .ShowMessage( LocalizationManager.GetLocalizedValue("StreamingErrorHeader"), LocalizationManager.GetLocalizedValue("StreamingErrorMsg")); } }
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) { _logger.Debug("Event handler started"); var tokenSource = new System.Threading.CancellationTokenSource(); try { tokenSource.CancelAfter(TimeSpan.FromMilliseconds(_timerInterval)); new System.Threading.Tasks.Task( () => { CheckProcesses(); tokenSource.Token.ThrowIfCancellationRequested(); return; }, tokenSource.Token).Wait(); } catch (AggregateException) { _logger.Error("Timespan exceeded checking the health of running processes. Verify WMI is A-OK and things aren't otherwise stacked up on this server."); } finally { tokenSource.Dispose(); } timer.Start(); _logger.Debug("Event handler completed"); }