public Window4() { InitializeComponent(); this.PlotModel = new PlotModel(); this.PlotModel.Series.Add(new FunctionSeries()); DataContext = this; var worker = new BackgroundWorker { WorkerSupportsCancellation = true }; double x = 0; worker.DoWork += (s, e) => { while (!worker.CancellationPending) { lock (this.PlotModel.SyncRoot) { this.PlotModel.Title = "Plot updated: " + DateTime.Now; this.PlotModel.Series[0] = new FunctionSeries(Math.Sin, x, x + 4, 0.01); } x += 0.1; PlotModel.InvalidatePlot(true); Thread.Sleep(100); } }; worker.RunWorkerAsync(); this.Closed += (s, e) => worker.CancelAsync(); }
/** * Method to implement the Search/Abort functionality. Each consecutive press of the button * changes the mode of operation of the button. * The status bar is used to display the current mode od operation. */ private void searchButton_Click(object sender, EventArgs e) { if (file == null) { MessageBox.Show("Please select a file before starting the search", "Error"); } else { if (button_flag == false) { listView1.Items.Clear(); b_worker.RunWorkerAsync(); searchButton.Text = "Cancel"; button_flag = true; toolStripStatusLabel1.Text = "Performing search..."; clearButton.Enabled = false; } else { b_worker.CancelAsync(); button_flag = false; searchButton.Text = "Search"; toolStripStatusLabel1.Text = "Ready for operation"; clearButton.Enabled = true; instancesFoundBox.Text = (listView1.Items.Count).ToString(); } } }
public void OnTimedEvent(object source, ElapsedEventArgs e) { Searcher.CancelAsync(); aTimer.Enabled = false; aTimer.Stop(); TabPage.displayError("Connection Timed Out. Please Check your Internet Connection."); }
/// <summary> /// 停止发送心跳包. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void Func2(object sender, EventArgs e) { if (backgroundWorker1.WorkerSupportsCancellation == true) { // Cancel the asynchronous operation. backgroundWorker1.CancelAsync(); } }
private void formClosingCallback(object sender, FormClosingEventArgs e) { if (backgroundWorker1.WorkerSupportsCancellation == true) { // Cancel the asynchronous operation. pauseBackgroundWorker = true; backgroundWorker1.CancelAsync(); } }
private void SystemTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (_systemTimer != null) { if (_systemTimer.Enabled) { _systemTimer.Stop(); } } worker.CancelAsync(); }
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { try { if (e.ColumnIndex >= 0 && this.dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "RunQuery") { BindingSource bindingSource = this.dataGridView1.DataSource as BindingSource; M2MMatrixCompressionPlugin.M2MMatrixCompressionStat item = bindingSource.Current as M2MMatrixCompressionPlugin.M2MMatrixCompressionStat; item.RunQuery = !item.RunQuery; //flip all with same SQL and intermediate MG name foreach (M2MMatrixCompressionPlugin.M2MMatrixCompressionStat stat in _list) { if (item.IntermediateMeasureGroupName == stat.IntermediateMeasureGroupName && item.SQL == stat.SQL) { stat.RunQuery = item.RunQuery; } } dataGridView1.Refresh(); if (item == currentStat) { if (!item.RunQuery) { backgroundWorker.CancelAsync(); try { lock (command) { command.Cancel(); } } catch { } } else { } } if (_complete) { _complete = false; FindWork(); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
private void okbutton_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(ImgBinFileInfo.ImageBinFileMD5Sum)) { StateChanged?.Invoke(this, ImgBinFileInfo); // SystemLog.I(TAG, ImgBinFileInfo); } if (CalFileMD5work != null && CalFileMD5work.WorkerSupportsCancellation) { CalFileMD5work?.CancelAsync(); } Dispose(); }
public void checkvideoEnd() { //If we check video end about normal case string sCurrentValue; sCurrentValue = _driver.FindElement(By.XPath("//*[@id='movie_player']")).GetAttribute("class"); _isVideoEnd = this.IsVideoEnded(sCurrentValue); //System.Diagnostics.Debug.WriteLine("Player State :", sCurrentValue); if (_isVideoEnd == true) { worker.CancelAsync(); } }
private void submit_Click(object sender, RoutedEventArgs e) { //only the admin can start the game //when the admin clickes the button the other players should be moved to the game room. //genrate a new game id; // send start game request. mainWindow.Client.startGameRequest(this.gameID); backgroundWorker1.CancelAsync(); _gameFrame.Navigate(new game(gameID)); }
public void StartSearch() { string query = searchentry1.Query; if (searchBackgoundWorker != null && searchBackgoundWorker.IsBusy) { searchBackgoundWorker.CancelAsync(); } if (string.IsNullOrEmpty(query)) { notebook1.Page = 1; return; } this.notebook1.Page = 2; switch (searchMode) { case SearchMode.Member: IdeApp.Workbench.StatusBar.BeginProgress(GettextCatalog.GetString("Searching member...")); break; case SearchMode.Disassembler: IdeApp.Workbench.StatusBar.BeginProgress(GettextCatalog.GetString("Searching string in disassembled code...")); break; case SearchMode.Decompiler: IdeApp.Workbench.StatusBar.BeginProgress(GettextCatalog.GetString("Searching string in decompiled code...")); break; case SearchMode.Type: IdeApp.Workbench.StatusBar.BeginProgress(GettextCatalog.GetString("Searching type...")); break; } memberListStore.Clear(); typeListStore.Clear(); searchBackgoundWorker = new BackgroundWorker(); searchBackgoundWorker.WorkerSupportsCancellation = true; searchBackgoundWorker.WorkerReportsProgress = false; searchBackgoundWorker.DoWork += SearchDoWork; searchBackgoundWorker.RunWorkerCompleted += delegate { searchBackgoundWorker = null; }; searchBackgoundWorker.RunWorkerAsync(query); }
public static void ExtractSin(BackgroundWorker sender, string sinfile, string outfile, bool log = true) { using (FileStream stream = new FileStream(sinfile, FileMode.Open, FileAccess.Read)) using (BinaryReader br = new BinaryReader(stream)) { if (log) Logger.WriteLog("Verifying extracted Sin File"); ; if (!SinFile.VerifySin(br)) { sender.CancelAsync(); return; } List<SinFile.BlockInfoHeader> bihs = null; int SinVer = SinFile.GetSinVersion(br); switch (SinVer) { case 2: bihs = SinFileV2.GetBIHs(br); break; case 3: bihs = SinFileV3.GetBIHs(br); break; } if (log) Logger.WriteLog("Extracting image from Sin File " + Path.GetFileName(sinfile)); SinExtract.ExtractSinData(sender, br, bihs, outfile, log); } }
private void BtCancel_Click(object sender, RoutedEventArgs e) { if ((null != bgWorker) && bgWorker.IsBusy) { bgWorker.CancelAsync(); } }
public void CancelAsyncNonBusy () { BackgroundWorker b = new BackgroundWorker (); b.WorkerSupportsCancellation = true; Assert.IsFalse (b.IsBusy, "#1"); b.CancelAsync (); }
MultiProgressDialog(string status, List<string> names, Action<ProgressDelegate, CancelDelegate> work, Action finished = null) { InitializeComponent(); Status = status; progress = names.Select(name => 0).ToList(); SetupGrid(names); worker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; worker.DoWork += (s, e) => { work((child, done, total) => SetProgress(child, done, total), forceCancel => { if (forceCancel) worker.CancelAsync(); if (worker.CancellationPending) e.Cancel = true; return e.Cancel; }); }; worker.ProgressChanged += (s, e) => { for (var ctr = 0; ctr < progressBars.Count; ++ctr) progressBars[ctr].Progress = progress[ctr]; }; worker.RunWorkerCompleted += (s, e) => { canClose = true; Close(); if (e.Error != null) throw new Exception($"Background task failed: {e.Error.Message}", e.Error); if ((!e.Cancelled) && (finished != null)) finished(); }; worker.RunWorkerAsync(); }
private void button_cancel_print_Click(object sender, RoutedEventArgs e) { if (printWorker.WorkerSupportsCancellation == true) { printWorker.CancelAsync(); } }
private void Process() { var pbViewModel = new ProgressBarViewModel(); var pbView = new ProgressBarView { DataContext = pbViewModel }; pbView.Show(); var worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.DoWork += worker_DoWork; worker.ProgressChanged += (sender, args) => { pbViewModel.Value = args.ProgressPercentage; }; worker.RunWorkerCompleted += (sender, args) => { if (args.Cancelled) { MessageBox.Show("Расчет прерван"); } pbView.Close(); }; pbViewModel.Cancelled += (sender, args) => { worker.CancelAsync(); }; worker.RunWorkerAsync(); }
public void CancleAsync() { if (!this.mainWorker.WorkerSupportsCancellation) { mainWorker.CancelAsync(); } }
public override bool Execute() { Log.LogMessage(string.Format("Starting to build '{0}'", ApplicationToBuild)); try { var aionBuilder = new AionBuilder(AionBuildProcess, null, Log); var worker = new BackgroundWorker(); worker.DoWork += WorkerDoWork; worker.WorkerSupportsCancellation = true; worker.RunWorkerAsync(); aionBuilder.Build(ApplicationToBuild, ShouldRestoreCodeFromApp, BuildTimeOutInSeconds); worker.CancelAsync(); Log.LogMessage(string.Format("Finished building '{0}'{1}", ApplicationToBuild, Environment.NewLine)); return aionBuilder.IsBuildSuccesful; } catch (Exception e) { Log.LogError(e.Message + " > " + e.StackTrace); return false; } }
public void Stop() { nf.AddToINFO($@"Closing Measurment."); Application.DoEvents(); measWorker.CancelAsync(); while (measWorker.CancellationPending) { nf.AddToINFO($@"Cancellation pending...", InfoLine); Thread.Sleep(1000); measWorker.Dispose(); Application.DoEvents(); } nf.AddToINFO($@"Measurment is closed.", InfoLine); WorkerEndOutput(); Application.DoEvents(); }
private void button9_Click(object sender, EventArgs e) { if (backgroundWorker2.WorkerSupportsCancellation == true) { // Cancel the asynchronous operation. backgroundWorker2.CancelAsync(); } }
void StopActiveSearch() { if (searchWorker != null) { searchWorker.CancelAsync(); } searchWorker = null; }
public void bwStopDataGrid(Object sender, EventArgs e) { if (bw.WorkerSupportsCancellation == true) { // Cancel the asynchronous operation. bw.CancelAsync(); // btnStart.Enabled = true; } }
private void SystemTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { //MessageBox.Show("System Timer Expire!"); _systemTimer.Stop(); //TOAN : 06/30/2019. 이제 일을 그만하자. worker.CancelAsync(); System.Diagnostics.Debug.WriteLine(string.Format("[Web Actor]system timer expired")); }
private void Stop10_Click(object sender, EventArgs e) { if (bw10.WorkerSupportsCancellation == true) { // Cancel the asynchronous operation. bw10.CancelAsync(); Start10.Enabled = true; } }
private void cancelAsyncButton_Click(object sender, EventArgs e) { if (backgroundWorker1.WorkerSupportsCancellation == true) { // Cancel the asynchronous operation. backgroundWorker1.CancelAsync(); } this.Close(); }
private void cmdTrennen_Click(System.Object sender, System.EventArgs e) { if (client.IsConnected) { client.LeaveChannel(txtChannel1.Text); } client.Disconnect(); backgroundWorker1.CancelAsync(); backgroundWorker1.Dispose(); }
/// <summary> /// Executed when the service starts /// </summary> /// <param name="args"></param> protected override void OnStart(string[] args) { serviceLog.WriteEntry("IntelliMailService started"); BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(StartIdleProcess); if (worker.IsBusy) worker.CancelAsync(); worker.RunWorkerAsync(); }
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { // Get the BackgroundWorker that raised this event. CallParameter cp3 = (CallParameter)e.Argument; //this.imagebox.BeginInvoke((Action)(() => // { // LoadHomeList_MultiThread(cp2.brandid, cp2.pagid); // })); e.Result = LoadHomeList_MultiThread(cp3.brandid, cp3.pagid, cp3.storey); backgroundWorker2.CancelAsync(); }
/// <summary> /// 取消文件传输 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCancel_Click(object sender, EventArgs e) { Result = "Info: 用户取消文件传输!"; if (backgroundUploadWorker != null && backgroundUploadWorker.IsBusy) { backgroundUploadWorker.CancelAsync(); } if (backgroundDownloadWorker != null && backgroundDownloadWorker.IsBusy) { backgroundDownloadWorker.CancelAsync(); } }
static void Main(string[] args) { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.WorkerSupportsCancellation = true; bw.RunWorkerAsync(); Console.WriteLine("Window closer started\nPress any key to exit..."); Console.ReadKey(); bw.CancelAsync(); bw.DoWork -= bw_DoWork; }
public DocumentUploader() { InitializeComponent(); CmsWebService service = new CmsWebService(); WindowsIdentity windowsUser = WindowsIdentity.GetCurrent(); if (windowsUser == null) { return; } List<string> temp = windowsUser.Name.Split('\\').ToList(); User user = service.GetUser(temp.Last()); ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["CmsEntities"]; EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder(settings.ConnectionString); SqlConnectionStringBuilder conn = new SqlConnectionStringBuilder(builder.ProviderConnectionString); lblTitle.Text = string.Format("Document Version Imports: by {0} into {1} on {2}", user.UserName, conn.InitialCatalog, conn.DataSource); mMetaData.UserId = user.Id; using (mWorker = new BackgroundWorker()) { mWorker.WorkerSupportsCancellation = true; mWorker.WorkerReportsProgress = true; mWorker.ProgressChanged += bw_ProgressChanged; mWorker.RunWorkerCompleted += bw_RunWorkerCompleted; mWorker.DoWork += (s1, e1) => { try { if (mWorker.CancellationPending) { mWorker.CancelAsync(); mWorker.Dispose(); } else { //WORK ImportDocuments(mWorker); } } catch (ThreadAbortException) { Thread.ResetAbort(); } }; } }
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { XmlDocument parsedStream = new XmlDocument(); parsedStream.Load(filepath); XmlNodeList nodes = parsedStream.DocumentElement.SelectNodes("T"); lines.Clear(); int count = 0; foreach (XmlNode node in nodes) { string str = ""; foreach (string s in new String[] { "O_ORDERKEY", "O_TOTALPRICE", "O_ORDERDATE" }) { str += node.SelectSingleNode(s).InnerText + "\t\t"; } lines.Add(str); if (backgroundWorker.CancellationPending == true) { backgroundWorker.CancelAsync(); return; } count++; if (backgroundWorker.CancellationPending) { e.Cancel = true; backgroundWorker.ReportProgress(0); return; } this.backgroundWorker.ReportProgress(count * 100 / nodes.Count); this.Dispatcher.Invoke((Action)(() => { this.UpdateLayout(); } )); } }
private void cancelAsync() { if (backgroundWorkerParser.WorkerSupportsCancellation == true) { // Cancel the asynchronous operation. backgroundWorkerParser.CancelAsync(); } if (backgroundWorkerSender.WorkerSupportsCancellation == true) { // Cancel the asynchronous operation. backgroundWorkerSender.CancelAsync(); } }
private void UpdateLviStatus(object sender, string msg, Task_Level level) { if (level == Task_Level.TASK_PASS) { mTaskStatus = level; } if (level == Task_Level.TASK_FAIL) { mTaskStatus = level; if (this.CcuWorkTask.IsBusy)//关闭正在运行的线程 { CcuWorkTask.CancelAsync(); Thread.Sleep(5); mCcuEvent.Set(); } } if (CcuLviHandler != null) { TaskArgs mArgs = new TaskArgs(); mArgs.msg = msg; mArgs.level = level; CcuLviHandler(sender, mArgs); } }
private void generateReport(List <string> Parsed) { //Cancel Previous Operaions if (backgroundWorkerReport.WorkerSupportsCancellation == true) { // Cancel the asynchronous operation. backgroundWorkerReport.CancelAsync(); } if (!backgroundWorkerReport.IsBusy) { // Start the asynchronous operation. backgroundWorkerReport.RunWorkerAsync(Parsed); } }
private bool Stop(bool bRestart) { Console.WriteLine("D: MainWindow Stop()"); if (buttonStop.IsEnabled == true && asio.GetStatus() == AsioCS.AsioStatus.Running) { backgroundWorker1.CancelAsync(); m_restart = bRestart; asio.Stop(); buttonStop.IsEnabled = false; return(true); } Console.WriteLine("D: MainWindow Stop() 空振り"); return(false); }
protected override void bulkOCRToolStripMenuItem_Click(object sender, RoutedEventArgs e) { if (backgroundWorkerBulk != null && backgroundWorkerBulk.IsBusy) { backgroundWorkerBulk.CancelAsync(); return; } BulkDialog bulkDialog = new BulkDialog(); bulkDialog.InputFolder = inputFolder; bulkDialog.OutputFolder = outputFolder; bulkDialog.OutputFormat = outputFormat; bulkDialog.DeskewEnabled = bulkDeskewEnabled; Nullable <bool> dialogResult = bulkDialog.ShowDialog(); if (dialogResult.HasValue && dialogResult.Value) { inputFolder = bulkDialog.InputFolder; outputFolder = bulkDialog.OutputFolder; outputFormat = bulkDialog.OutputFormat; bulkDeskewEnabled = bulkDialog.DeskewEnabled; this.statusLabel.Content = Properties.Resources.OCRrunning; Mouse.OverrideCursor = Cursors.Wait; this.Cursor = Cursors.Wait; this.textBox1.Cursor = Cursors.Wait; this.toolStripProgressBar1.IsEnabled = true; this.toolStripProgressBar1.Visibility = Visibility.Visible; this.bulkOCRToolStripMenuItem.Header = Properties.Resources.CancelBulkOCR; if (!this.statusForm.IsVisible) { this.statusForm.Show(); } else if (this.statusForm.WindowState == WindowState.Minimized) { this.statusForm.WindowState = WindowState.Normal; } this.statusForm.Activate(); this.statusForm.TextBox.AppendText("\t-- " + Properties.Resources.Beginning_of_task + " --" + Environment.NewLine); // start bulk OCR stopWatch.Start(); this.backgroundWorkerBulk.RunWorkerAsync(); } }
private void stopButton_Click(object sender, EventArgs e) { try { // Notify the acquisition thread we are stopping acquisitionWorker.CancelAsync(); // Stop the acquisition. This will cause the acquisition // thread to get an "acquisition stopped" error if it is // blocked waiting for an image _session.Acquisition.Stop(); } catch (ImaqdxException error) { MessageBox.Show(error.ToString(), "NI-IMAQdx Error"); } }
public void Generate(int size, RenderContext context) { m_Context = context; m_Worker = new BackgroundWorker(); m_Worker.WorkerReportsProgress = true; m_Worker.WorkerSupportsCancellation = true; m_Worker.DoWork += bgw_DoWork; //Work Event m_Worker.RunWorkerCompleted += m_Worker_RunWorkerCompleted; //Event that is run in the background; Console.WriteLine("Opening new Thread"); m_Worker.RunWorkerAsync(size); m_Worker.CancelAsync(); m_Worker.Dispose(); }
static void Main(string[] args) { var bw = new BackgroundWorker(); bw.WorkerReportsProgress = true; bw.WorkerSupportsCancellation = true; bw.DoWork += Worker_DoWork; bw.ProgressChanged += Worker_ProgressChanged; bw.RunWorkerCompleted += Worker_Completed; bw.RunWorkerAsync(); Console.WriteLine("Press C to cancel work"); do { if (Console.ReadKey(true).KeyChar == 'C') { bw.CancelAsync(); } } while(bw.IsBusy); }
private void GetComputerMoveAsynchronously() { var bw = new BackgroundWorker(); // define the event handlers bw.DoWork += (sender, args) => { int winner = gameBrain.CheckForWin(); if (!gameBrain.MakeComputerMove()) bw.CancelAsync(); }; bw.RunWorkerCompleted += (sender, args) => { if (args.Error != null) // if an exception occurred during DoWork, MessageBox.Show(args.Error.ToString()); // do your error handling here //Update GUI player int computerMove = gameBrain.GetComputerMove(); Rectangle rec = (Rectangle)Board.Children[computerMove]; rec.Fill = computerPlayer.Fill; int winner = gameBrain.CheckForWin(); if (winner != 0) ShowWinner(winner); else GetComputerRotation(); }; bw.RunWorkerAsync(); }
static void Main(string[] arg) { _bw = new BackgroundWorker { WorkerReportsProgress = true, // 报告工作的进度 WorkerSupportsCancellation = true // 支持异步的取消工作 }; _bw.DoWork += bw_DoWork; _bw.ProgressChanged += bw_ProgressChanged; _bw.RunWorkerCompleted += bw_RunWorkerCompleted; _bw.RunWorkerAsync("Hello to worker"); // 开始执行 Console.WriteLine("Press Enter in the next 5 seconds to cancel."); Console.ReadLine(); if (_bw.IsBusy) _bw.CancelAsync(); // 设置 CancellationPending 为 true Console.ReadLine(); }
/// <summary> /// Imports masters tapes from file. /// </summary> /// <param name="worker">The worker.</param> /// <param name="e">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param> private void ImportMasters(BackgroundWorker worker, DoWorkEventArgs e) { Stream importStream = null; //Master List import, has a popup to enter Master Tape to add to List<MasterListValues> masterListValues = DataBaseControls.GetAllMasterListItems(); string[] cameraValues = commonMethod.CameraDropdownItems(); string masterTapeName = ""; string cameraMasterName = ""; bool addMasters = false; //create a new form for user to enter tape name Form masterPrompt = new Form(); masterPrompt.Height = 200; masterPrompt.Width = 500; masterPrompt.SizeGripStyle = SizeGripStyle.Hide; masterPrompt.FormBorderStyle = FormBorderStyle.FixedSingle; masterPrompt.StartPosition = FormStartPosition.CenterScreen; masterPrompt.Text = "Enter Tape Name"; //Set up items to add to popup box Label textLabel = new Label() { Left = 50, Top = 20, Text = "Master Archive to Import" }; ComboBox inputBox = new ComboBox() { Left = 50, Top = 50, Width = 400 }; //add items to combobox foreach (MasterListValues values in masterListValues) { inputBox.Items.Add(values.MasterArchive); } inputBox.SelectedIndex = 0; //add media combobox ComboBox mediaCombo = new ComboBox() { Left = 50, Top = 75, Width = 200 }; //add items to combobox foreach (string mediaValue in cameraValues) { mediaCombo.Items.Add(mediaValue); } mediaCombo.SelectedIndex = 1; mediaCombo.KeyPress += (senderCombo, eCombo) => { eCombo.Handled = true; }; mediaCombo.SelectedIndexChanged += (senderCombo, eCombo) => { textLabel.Focus(); }; //Check for names in the filename #region Check for names in File try { //check to make sure there is something selected if (!ofd.FileName.Equals(string.Empty)) { //get name of file without extension string nameFile = Path.GetFileNameWithoutExtension(ofd.FileName); //get index of the word master int index = nameFile.ToLower().IndexOf("master"); if(index != -1) { //get substring to include "master ddd" nameFile = nameFile.Substring(index); //check to make sure the last character is a digit while (!char.IsDigit(nameFile[nameFile.Length - 1])) { nameFile = nameFile.Remove(nameFile.Length - 1, 1); } //convert name to lowercasse and then camelcase TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; nameFile = textInfo.ToTitleCase(nameFile.ToLower()); //add name of master tape if not included if (!inputBox.Items.Contains(nameFile)) { inputBox.Items.Add(nameFile); } inputBox.Text = nameFile; } } } catch { Debug.WriteLine("Error in master gather"); } //check if there is a media defined in the name using all combobox items try { //check to make sure there is something selected if (!ofd.FileName.Equals(string.Empty)) { //get name of file without extension foreach (string obj in mediaCombo.Items) { Debug.WriteLine("In media for loop"); if (!obj.ToLower().Equals("other")) { Debug.WriteLine("Does not equal other"); //string[] mediaItems = mediaCombo.DataSource.t string nameFile = Path.GetFileNameWithoutExtension(ofd.FileName); //get index of the word master int index = nameFile.ToLower().IndexOf(obj.ToLower()); //add name of master tape if not included if (index != -1) { Debug.WriteLine("Does not equal -1"); mediaCombo.Text = obj; break; } } } } } catch { Debug.WriteLine("Error in media gather"); } #endregion //Set up buttons to add Button confirmation = new Button() { Text = "OK", Left = 240, Width = 100, Top = 120 }; Button cancelButton = new Button() { Text = "Cancel", Left = 350, Width = 100, Top = 120 }; //button actions cancelButton.Click += (senderPrompt, ePrompt) => { addMasters = false; masterPrompt.Close(); }; confirmation.Click += (senderPrompt, ePrompt) => { addMasters = true; masterTapeName = inputBox.Text; cameraMasterName = mediaCombo.Text; masterPrompt.Close(); }; //Add items to form masterPrompt.Controls.Add(textLabel); masterPrompt.Controls.Add(inputBox); masterPrompt.Controls.Add(mediaCombo); masterPrompt.Controls.Add(confirmation); masterPrompt.Controls.Add(cancelButton); masterPrompt.ShowDialog(); //Add entries or Cancel depending on button clicked if (addMasters) { //gets extension of the file and acts accordingly switch (GetExtensionOfFile(ofd)) { case "csv": UpdateStatusBarBottom("Importing " + masterTapeName + " Entries"); DataBaseControls.AddMasterTapesFromFile(worker, importStream, ofd, masterTapeName, commonMethod.GetCameraNumber(cameraMasterName)); break; case "txt": ofd.FileName = @"" + TempConvertToCSV(ofd); UpdateStatusBarBottom("Importing " + masterTapeName + " Entries"); DataBaseControls.AddMasterTapesFromFile(worker, importStream, ofd, masterTapeName, commonMethod.GetCameraNumber(cameraMasterName), true); break; case "doc": case "docx": ofd.FileName = @"" + ConvertWordToCSVFile(ofd); UpdateStatusBarBottom("Importing " + masterTapeName + " Entries"); DataBaseControls.AddMasterTapesFromFile(worker, importStream, ofd, masterTapeName, commonMethod.GetCameraNumber(cameraMasterName), true); break; default: Debug.WriteLine("File was not a txt, doc, docx, or csv"); break; } } else { worker.CancelAsync(); if (worker.CancellationPending) { e.Cancel = true; return; } } }
internal void Merge() { Type ilMergeType = null; Type ilMergeKind = null; try { Assembly assembly = Assembly.LoadFrom(Settings.Default.ILMergePath); ilMergeType = assembly.GetType("ILMerging.ILMerge"); ilMergeKind = assembly.GetType("ILMerging.ILMerge+Kind"); } catch (Exception e) { OnError("Can't create ILMerge object.", e); return; } try { //Create ILMerge object Object[] args = new Object[] { }; Object obj = ilMergeType.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, args); ilMergeType.InvokeMember("Log", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { Settings.Default.ShouldLog }); Object objKind = ilMergeKind.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, args); ilMergeKind.InvokeMember("value__", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.SetField, null, objKind, new Object[] { (int)Settings.Default.TargetKind }); ilMergeType.InvokeMember("TargetKind", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { objKind }); ilMergeType.InvokeMember("AllowWildCards", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { Settings.Default.AllowWildCards }); ilMergeType.InvokeMember("AllowZeroPeKind", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { Settings.Default.AllowZeroPEKind }); ilMergeType.InvokeMember("Closed", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { Settings.Default.Closed }); PropertyInfo pi = ilMergeType.GetProperty("XmlDocumentation"); if (pi != null) { ilMergeType.InvokeMember("XmlDocumentation", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { Settings.Default.XmlDocumentation }); } ilMergeType.InvokeMember("CopyAttributes", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { Settings.Default.CopyAttributes }); ilMergeType.InvokeMember("DebugInfo", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { Settings.Default.DebugInfo }); ilMergeType.InvokeMember("Internalize", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { Settings.Default.Internalize }); ilMergeType.InvokeMember("PublicKeyTokens", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { Settings.Default.PublicKeyTokens }); pi = ilMergeType.GetProperty("DelaySign"); if (pi != null) { ilMergeType.InvokeMember("DelaySign", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { Settings.Default.DelaySign }); } pi = ilMergeType.GetProperty("AllowDuplicateType"); if (Settings.Default.AllowDuplicateType && pi != null) { object[] dublArgs; if (Settings.Default.DuplicateTypeName == "All types") dublArgs = new object[] { null }; else dublArgs = new object[] { Settings.Default.DuplicateTypeName }; ilMergeType.InvokeMember("AllowDuplicateType", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, dublArgs); } pi = ilMergeType.GetProperty("Version"); if (pi != null && Settings.Default.Version.Trim() != "") { Version version = new Version(Settings.Default.Version); ilMergeType.InvokeMember("Version", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { version }); } if (!string.IsNullOrEmpty(KeyFile)) { ilMergeType.InvokeMember("SnkFile", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { KeyFile }); } if (!string.IsNullOrEmpty(AttributeFile)) { ilMergeType.InvokeMember("AttributeFile", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { AttributeFile }); } if (!string.IsNullOrEmpty(ExcludeFile)) { ilMergeType.InvokeMember("ExcludeFile", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { ExcludeFile }); } if (!string.IsNullOrEmpty(LogFile)) { ilMergeType.InvokeMember("LogFile", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { LogFile }); } ilMergeType.InvokeMember("OutputFile", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { OutputFile }); string[] assemblies = new string[OtherAssemblies.Count + 1]; assemblies[0] = PrimaryAssembly; int i = 1; foreach (string item in OtherAssemblies ) { assemblies[i] = item; i++; } ilMergeType.InvokeMember("SetInputAssemblies", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, new Object[] { assemblies }); BackgroundWorker logReaderWorker = new BackgroundWorker(); logReaderWorker.DoWork += new DoWorkEventHandler(logReaderWorker_DoWork); logReaderWorker.WorkerSupportsCancellation = true; logReaderWorker.RunWorkerAsync(); ilMergeType.InvokeMember("Merge", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, new Object[] { }); obj = null; objKind = null; ilMergeType = null; ilMergeKind = null; logReaderWorker.CancelAsync(); } catch (Exception ex) { OnError("Merge error", ex); } }
public void Backgrounf_worker_cancellation_and_progress() { var backgroundWorker = new BackgroundWorker {WorkerReportsProgress = true, WorkerSupportsCancellation = true}; backgroundWorker.DoWork += (sender, args) => { for (var i = 0; i < 100; i += 20) { if (backgroundWorker.CancellationPending) { args.Cancel = true; return; } backgroundWorker.ReportProgress(i); Thread.Sleep(1000); } args.Result = 123; }; backgroundWorker.ProgressChanged += (sender, args) => Console.WriteLine("Reached " + args.ProgressPercentage + "%"); backgroundWorker.RunWorkerCompleted += (sender, args) => { if (args.Cancelled) { Console.WriteLine("You cancelled!"); } else if (args.Error != null) { Console.WriteLine("Worker Exception: " + args.Error.ToString()); } else { Console.WriteLine("Completed: " + args.Result); } }; backgroundWorker.RunWorkerAsync("Hello to worker"); Thread.Sleep(2000); if(backgroundWorker.IsBusy) backgroundWorker.CancelAsync(); Thread.Sleep(1100); //wait for last loop }
private void LoadSparesInBackground() { ParentWindow.edtStatus.Content = "загрузка..."; SelectedSpareID = 0; if (dgSpares.SelectedItem != null) SelectedSpareID = (dgSpares.SelectedItem as SpareView).id; BackgroundLoad = new BackgroundWorker(); BackgroundLoad.DoWork += new DoWorkEventHandler(BackgroundLoad_DoWork); BackgroundLoad.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundLoad_RunWorkerCompleted); if (BackgroundLoad.IsBusy) BackgroundLoad.CancelAsync(); BackgroundLoad.RunWorkerAsync(); }
private void ShowSpareDetailsInBackground(IList selectedItems) { ParentWindow.edtStatus.Content = "загрузка"; BackgroundShowDetails = new BackgroundWorker(); BackgroundShowDetails.DoWork += new DoWorkEventHandler(BackgroundShowDetails_DoWork); BackgroundShowDetails.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundShowDetails_RunWorkerCompleted); if (BackgroundShowDetails.IsBusy) BackgroundShowDetails.CancelAsync(); BackgroundShowDetails.RunWorkerAsync(selectedItems); }
private void StartContentBuilding() { BackgroundWorker worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; #region Events worker.DoWork += delegate(object s, DoWorkEventArgs args) { EditorStatus = EditorStatus.LOADING; Database.Instance.LoadData(); progressStatusBarItem.Dispatcher.Invoke( System.Windows.Threading.DispatcherPriority.Normal, new Action( delegate() { progressStatusBarItem.Content = "Building content..."; } )); #region Resource Builder Events ResourceBuilder.Instance.OnPercentChanged += new EventHandler<OnPercentChangedEventArgs>(delegate(object o, OnPercentChangedEventArgs OnPercentChangedEventArgs) { worker.ReportProgress(OnPercentChangedEventArgs.Percent); }); ResourceBuilder.Instance.OnBuildFailed += new EventHandler<EventArgs>(delegate(object onBuildFailed, EventArgs onBuildFailedArgs) { worker.CancelAsync(); }); #endregion ResourceBuilder.Instance.BuildContent(); }; worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args) { int percentage = args.ProgressPercentage; progressBar.Value = percentage; }; worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args) { EditorStatus = EditorStatus.IDLE; progressStatusBarItem.Content = "Ready"; progressBar.Value = 0; Output.AddToOutput("Building of content files completed..."); sceneGraph.Lighting.LoadContent(); gizmo = new GizmoModules.GizmoComponent(GameApplication.Instance.GetGraphics(), spriteBatch); gizmo.SetSelectionPool(WorldManager.Instance.GetActors().Values); gizmo.ActiveSpace = GizmoModules.TransformSpace.Local; gizmo.TranslateEvent += new GizmoModules.TransformationEventHandler(gizmo_TranslateEvent); gizmo.RotateEvent += new TransformationEventHandler(GizmoRotateEvent); gizmo.ScaleEvent += new TransformationEventHandler(GizmoScaleEvent); // Set up the frame update timer timer = new Timer(); xnaControl.ResetMouseState(); }; #endregion worker.RunWorkerAsync(); }
public void CancelAsyncNoCancellationSupported () { BackgroundWorker b = new BackgroundWorker (); Assert.IsFalse (b.IsBusy, "#1"); b.CancelAsync (); }
private void GetComputerMoveAsynchronously() { var bw = new BackgroundWorker(); // define the event handlers bw.DoWork += (sender, args) => { Console.WriteLine("Started AI thread."); int winner = gameBrain.CheckForWin(); if (!gameBrain.MakeComputerMove() || winner != 0) { Console.WriteLine("Cancelled AI thread."); bw.CancelAsync(); if (winner != 0) ShowWinner(winner); } }; bw.RunWorkerCompleted += (sender, args) => { if (args.Error != null) // if an exception occurred during DoWork, { Console.WriteLine("Something went wrong with AI thread."); MessageBox.Show(args.Error.ToString()); // do your error handling here } Console.WriteLine("Good with AI thread."); int winner = gameBrain.CheckForWin(); if (winner == 0) { //Update GUI player int computerMove = gameBrain.GetComputerMove(); Rectangle rec = (Rectangle)Board.Children[computerMove]; rec.Fill = computerPlayer.Image; RePaintBoard(); winner = gameBrain.CheckForWin(); if (winner != 0) ShowWinner(winner); else GetComputerRotation(); } else if (winner != 0) { RePaintBoard(); ShowWinner(winner); } }; bw.RunWorkerAsync(); }
/// <summary> /// Initiates a single form publishing process /// </summary> private void DoPublish() { UserPublishGuid = Guid.NewGuid(); txtSurveyName.Enabled = false; txtSurveyID.Enabled = false; txtOrganization.Enabled = false; txtDepartment.Enabled = false; txtIntroductionText.Enabled = false; txtExitText.Enabled = false; dtpSurveyClosingDate.Enabled = false; txtOrganizationKey.Enabled = false; btnPrevious.Enabled = false; txtStatus.Clear(); txtURL.Clear(); this.tabPublishWebForm.SelectedTab = this.tabPublishWebForm.TabPages[2]; btnPublishForm.Enabled = true; progressBar.Visible = true; stopwatch = new Stopwatch(); stopwatch.Start(); Epi.Web.Common.Message.PublishRequest Request = new Epi.Web.Common.Message.PublishRequest(); if (string.IsNullOrEmpty(ClosingTimecomboBox.Text)) { Request.SurveyInfo.ClosingDate = dtpSurveyClosingDate.Value.Date + new TimeSpan(0, 23, 59, 0); } else { Request.SurveyInfo.ClosingDate = GetdateTimeFormat(dtpSurveyClosingDate.Value.Date, ClosingTimecomboBox.Text); } if (string.IsNullOrEmpty(StartTimecomboBox.Text)) { Request.SurveyInfo.StartDate = StartDateDatePicker.Value.Date; } else { Request.SurveyInfo.StartDate = GetdateTimeFormat(StartDateDatePicker.Value.Date, StartTimecomboBox.Text); } Request.SurveyInfo.DepartmentName = txtDepartment.Text; Request.SurveyInfo.IntroductionText = txtIntroductionText.Text; Request.SurveyInfo.ExitText = txtExitText.Text; Request.SurveyInfo.SurveyName = txtSurveyName.Text; Request.SurveyInfo.OrganizationKey = new Guid(txtOrganizationKey.Text.ToString()); Request.SurveyInfo.UserPublishKey = UserPublishGuid; Request.SurveyInfo.XML = template; Request.SurveyInfo.IsDraftMode = true; Request.SurveyInfo.SurveyType = (rdbSingleResponse.Checked) ? 1 : 2; if (txtOrganization.Text.Equals("Your Organization Name (optional)", StringComparison.OrdinalIgnoreCase)) { Request.SurveyInfo.OrganizationName = null; } else { Request.SurveyInfo.OrganizationName = txtOrganization.Text; } if (txtSurveyID.Text.Equals("Your Survey ID (optional)", StringComparison.OrdinalIgnoreCase)) { Request.SurveyInfo.SurveyNumber = null; } else { Request.SurveyInfo.SurveyNumber = txtSurveyID.Text; } Configuration config = Configuration.GetNewInstance(); try { if (config.Settings.Republish_IsRepbulishable) { Request.SurveyInfo.IsDraftMode = true; } else { Request.SurveyInfo.IsDraftMode = false; } } catch (Exception ex) { Request.SurveyInfo.IsDraftMode = false; } try { Epi.Web.Common.Message.PublishResponse Result = new Epi.Web.Common.Message.PublishResponse(); lock (syncLock) { this.Cursor = Cursors.WaitCursor; publishWorker = new BackgroundWorker(); publishWorker.WorkerSupportsCancellation = true; publishWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(worker_DoWork); publishWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(worker_WorkerCompleted); object[] args = new object[2]; args[0] = Request; args[1] = Result; publishWorker.RunWorkerAsync(args); } if (publishWorker.WorkerSupportsCancellation) { publishWorker.CancelAsync(); } } catch (Exception ex) { txtStatusSummary.AppendText("An error occurred while trying to publish the survey."); txtStatus.AppendText(ex.ToString()); btnDetails.Visible = true; this.progressBar.Visible = false; this.Cursor = Cursors.Default; } }
private void _workerTotalProcess_DoWork(object sender, DoWorkEventArgs e) { _worker2 = sender as BackgroundWorker; _index = _index + 1; _checkImportDone = new DelImportProcess(ImportProcess); IAsyncResult ar = _checkImportDone.BeginInvoke(new AsyncCallback(ImportComplete), new object()); while (!ar.IsCompleted) { ar.AsyncWaitHandle.WaitOne(1, false); } if (ar.IsCompleted == true) { if (_rImport == true) { //_workerTotalProcess_RunWorkerCompleted(sender, new RunWorkerCompletedEventArgs(ar.AsyncState, null, false)); } else { e.Cancel = true; _worker2.CancelAsync(); return; } } if (_worker2.CancellationPending) { e.Cancel = true; return; } }
private void matchingOnlyToolStripMenuItem_Click(object sender, EventArgs e) { try { OpenXsd(1); } catch (NineDragons.XStringDatabase.Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } mergeWorker = new BackgroundWorker(); mergeWorker.WorkerSupportsCancellation = true; mergeWorker.DoWork += new DoWorkEventHandler(this.MergeWorker_DoWork); mergeWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.MergeWorker_RunWorkerCompleted); busySectionPanel.Visible = true; if (mergeWorker.IsBusy && mergeWorker.WorkerSupportsCancellation) mergeWorker.CancelAsync(); else mergeWorker.RunWorkerAsync(new MergeXsdDelegate(DelegateMergeXsd)); }
private void PerformAction(string actionName, Project project, Cloud cloud, ProjectDirectories dir, Action<IVcapClient, DirectoryInfo> action) { var worker = new BackgroundWorker(); Messenger.Default.Register<NotificationMessageAction<string>>(this, message => { if (message.Notification.Equals(Messages.SetProgressData)) message.Execute(actionName); }); var window = new ProgressDialog(); var dispatcher = window.Dispatcher; var helper = new WindowInteropHelper(window); helper.Owner = (IntPtr)(dte.MainWindow.HWnd); worker.WorkerSupportsCancellation = true; worker.DoWork += (s, args) => { if (worker.CancellationPending) { args.Cancel = true; return; } Messenger.Default.Send(new ProgressMessage(0, "Starting " + actionName)); if (worker.CancellationPending) { args.Cancel = true; return; } if (!Directory.Exists(dir.StagingPath)) { dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(10, "Creating Staging Path")))); Directory.CreateDirectory(dir.StagingPath); } if (worker.CancellationPending) { args.Cancel = true; return; } if (Directory.Exists(dir.DeployFromPath)) { dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(10, "Creating Precompiled Site Path")))); Directory.Delete(dir.DeployFromPath, true); } if (worker.CancellationPending) { args.Cancel = true; return; } dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(30, "Preparing Compiler")))); VsWebSite.VSWebSite site = project.Object as VsWebSite.VSWebSite; if (site != null) { site.PreCompileWeb(dir.DeployFromPath, true); } else { string frameworkPath = (site == null) ? project.GetFrameworkPath() : String.Empty; if (worker.CancellationPending) { args.Cancel = true; return; } string objDir = Path.Combine(dir.ProjectDirectory, "obj"); if (Directory.Exists(objDir)) { Directory.Delete(objDir, true); // NB: this can cause precompile errors } var process = new System.Diagnostics.Process() { StartInfo = new ProcessStartInfo() { FileName = Path.Combine(frameworkPath, "aspnet_compiler.exe"), Arguments = String.Format("-nologo -v / -p \"{0}\" -f -u -c \"{1}\"", dir.ProjectDirectory, dir.DeployFromPath), CreateNoWindow = true, ErrorDialog = false, UseShellExecute = false, RedirectStandardOutput = true } }; if (worker.CancellationPending) { args.Cancel = true; return; } dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(40, "Precompiling Site")))); process.Start(); string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); if (process.ExitCode != 0) { string message = "Asp Compile Error"; if (false == String.IsNullOrEmpty(output)) { message += ": " + output; } dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressError(message)))); return; } } dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(50, "Logging in to Cloud Foundry")))); if (worker.CancellationPending) { args.Cancel = true; return; } var client = new VcapClient(cloud); try { client.Login(); } catch (Exception e) { dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressError("Failure: " + e.Message)))); return; } dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(75, "Sending to " + cloud.Url)))); if (worker.CancellationPending) { args.Cancel = true; return; } try { action(client, new DirectoryInfo(dir.DeployFromPath)); } catch (Exception e) { dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressError("Failure: " + e.Message)))); return; } dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(100, actionName + " complete.")))); }; worker.RunWorkerAsync(); if (!window.ShowDialog().GetValueOrDefault()) { worker.CancelAsync(); } }
private bool OpenXsd(int xsdIndex) { string filename = OpenXsdDialog(); if (filename == string.Empty) return false; if (xsdIndex == 0) xsd.Clear(); if (xsdIndex > 0 && !(xsd[0] is Xsd)) MessageBox.Show("Cannot open additional XSDs. Try loading an XSD.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); xsd.Insert(xsdIndex, (new XsdFile(filename, keys))); if (xsdIndex == 0) { loadWorker = new BackgroundWorker(); loadWorker.WorkerSupportsCancellation = true; loadWorker.DoWork += new DoWorkEventHandler(this.LoadWorker_DoWork); loadWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.LoadWorker_RunWorkerCompleted); busySectionPanel.Visible = true; if (loadWorker.IsBusy && loadWorker.WorkerSupportsCancellation) loadWorker.CancelAsync(); else loadWorker.RunWorkerAsync(xsdIndex); } else { xsd[xsdIndex].load(); } return true; }
public static int getCPUCores() { BackgroundWorker bw1 = new BackgroundWorker(); bw1.WorkerSupportsCancellation = true; threadsCounter = 0; bw1.DoWork += new DoWorkEventHandler(bw_DoWork); bw1.RunWorkerAsync(); System.Threading.Thread.Sleep(200); int singleThreadCount = threadsCounter; bw1.CancelAsync(); threadsCounter = 0; BackgroundWorker[] bwm = new BackgroundWorker[8]; for (int i = 0; i < 8; i++) { bwm[i] = new BackgroundWorker(); bwm[i].WorkerSupportsCancellation = true; bwm[i].DoWork += new DoWorkEventHandler(bw_DoWork); bwm[i].RunWorkerAsync(); } System.Threading.Thread.Sleep(200); int eightThreadsCount = threadsCounter; for (int i = 0; i < 8; i++) { bwm[i].CancelAsync(); } float performanceRatio = (float)eightThreadsCount / singleThreadCount; int cpuCores = 1; if (performanceRatio > 7) { cpuCores = 8; } else if (performanceRatio > 3.5) { cpuCores = 4; } else if (performanceRatio > 1.7) { cpuCores = 2; } return cpuCores; }
public void Button_Click(object sender, View.ViewButton eventHandler) { Debug.WriteLine(eventHandler.ToString() + " Clicked"); switch (eventHandler) { case View.ViewButton.RandomMap: mapType = Map.MapType.Random; break; case View.ViewButton.EmptyMap: mapType = Map.MapType.Empty; break; case View.ViewButton.ResetMap: DrawingControl.SuspendDrawing(view.getPanelMap()); model.Reset(true); DrawingControl.ResumeDrawing(view.getPanelMap()); break; } switch (eventHandler) { case View.ViewButton.RandomMap: case View.ViewButton.EmptyMap: /* save the temp variables */ model.getSimulation().set(View.ViewNumericUpDown.MapSize, tempMapSize); model.getSimulation().setCellSize(view.PANEL_SIZE / tempMapSize); model.getSimulation().set(View.ViewNumericUpDown.PercentWalkable, tempPercentWalkable); model.getSimulation().set(View.ViewNumericUpDown.NumberOfAgents, tempNumberofAgents); /* generate map */ generateMapCommon(null, true); /* initialize the node edit variables */ nodeEditStartAgentId = Agent.AgentID.Agent_0; nodeEditFinishAgentId = Agent.AgentID.Agent_0; nodeEditBackColor = model.getAgent(Agent.AgentID.Agent_0).getColor(Agent.ColorType.BackColor); nodeEditForeColor = model.getAgent(Agent.AgentID.Agent_0).getColor(Agent.ColorType.ForeColor); /* update view */ view.updateAgentItems(); view.getButton(View.ViewButton.Start).Enabled = true; view.getRadioButton(View.ViewRadioButton.EditWalkable).Enabled = true; view.getRadioButton(View.ViewRadioButton.EditNonWalkable).Enabled = true; view.setStatusText("Change Parameters, Edit Map, or Click Start"); view.buttonEditStartUpdate(nodeEditBackColor, nodeEditForeColor, "S", true); view.buttonEditFinishUpdate(nodeEditBackColor, nodeEditForeColor, "F", true); break; case View.ViewButton.Start: cancelled = false; nodeEditState = NodeEditState.DISABLED; model.getMap().setNodes(Node.Cost.Movement, 0.0); model.getMap().setNodes(Node.Cost.Heuristic, 0.0); model.getMap().setNodes(Node.Cost.Total, 0.0); foreach (Agent agent in model.getAgents()) { agent.getMap().setNodes(Node.Cost.Movement, 0.0); agent.getMap().setNodes(Node.Cost.Heuristic, 0.0); agent.getMap().setNodes(Node.Cost.Total, 0.0); agent.getMap().setNodes(Node.Flag.IsWalkable, true); agent.getMap().setNodes(Node.Flag.IsVisible, false); agent.getMap().setNodes(Node.Flag.IsShared, false); } /* update the view */ view.setStatusText(""); view.getButton(View.ViewButton.Cancel).Enabled = true; view.getButton(View.ViewButton.Start).Enabled = false; view.getButton(View.ViewButton.RandomMap).Enabled = false; view.getButton(View.ViewButton.EmptyMap).Enabled = false; view.controlEnable(false); view.getComboBox(View.ViewComboBox.Visualizations).Enabled = false; DrawingControl.SuspendDrawing(view.getPanelMap()); model.Reset(false); DrawingControl.ResumeDrawing(view.getPanelMap()); synchronization = new Synchronization(model.getSimulation().get(View.ViewNumericUpDown.NumberOfAgents)); /* start the agent background threads */ foreach (Agent agent in model.getAgents()) { running++; agent.setNode(Agent.NodeType.Current, agent.getNode(Agent.NodeType.Start)); agent.setNode(Agent.NodeType.Target, agent.getNode(Agent.NodeType.Finish)); agent.getMap().setNodes(Node.Flag.IsPath, false); agent.getNode(Agent.NodeType.Start).setFlag(Node.Flag.IsWalkable, true); agent.getNode(Agent.NodeType.Finish).setFlag(Node.Flag.IsWalkable, true); BackgroundWorker bgw = new BackgroundWorker(); bgw.WorkerSupportsCancellation = true; bgw.DoWork += new DoWorkEventHandler(Start_DoWork); bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Start_RunWorkerCompleted); bgw.RunWorkerAsync(agent); workers.Add(bgw); } /* init the parameters for un-applied map changes */ view.getNumericUpDown(View.ViewNumericUpDown.MapSize).Value = model.getSimulation().get(View.ViewNumericUpDown.MapSize); view.getNumericUpDown(View.ViewNumericUpDown.PercentWalkable).Value = model.getSimulation().get(View.ViewNumericUpDown.PercentWalkable); view.getNumericUpDown(View.ViewNumericUpDown.NumberOfAgents).Value = model.getSimulation().get(View.ViewNumericUpDown.NumberOfAgents); break; case View.ViewButton.Cancel: cancelled = true; view.getButton(View.ViewButton.Cancel).Enabled = false; view.getButton(View.ViewButton.Start).Enabled = true; view.getButton(View.ViewButton.RandomMap).Enabled = true; view.getButton(View.ViewButton.EmptyMap).Enabled = true; view.controlEnable(true); foreach (BackgroundWorker bgw in workers) { bgw.CancelAsync(); } break; case View.ViewButton.ExportCsv: StringBuilder result = new StringBuilder(); SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "*.csv|"; saveFileDialog.OverwritePrompt = true; if (saveFileDialog.ShowDialog() == DialogResult.OK && saveFileDialog.FileName != null) { ListView listView = view.getSimulationListView(); /* export the column headers */ foreach (ColumnHeader ch in listView.Columns) result.Append(ch.Text + ","); result.AppendLine(); /* export the data rows */ foreach (ListViewItem listItem in listView.Items) { foreach (ListViewItem.ListViewSubItem lvs in listItem.SubItems) result.Append(lvs.Text + ","); result.AppendLine(); } try { File.WriteAllText(saveFileDialog.FileName + ".csv", result.ToString()); } catch (Exception ex) { MessageBox.Show(ex.Message, "CSV Export Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } break; case View.ViewButton.ClearResults: model.getResults().clear(); break; } }
private void GetComputerMoveAsynchronously() { BackgroundWorker AIbackgroundWorker = new BackgroundWorker(); // define the event handlers AIbackgroundWorker.DoWork += (sender, args) => { //Console.WriteLine("Started AI thread."); int winner = gameBrain.CheckForWin(); if (winner != 0 || !gameBrain.MakeComputerMove()) { //Console.WriteLine("Cancelled AI thread."); AIbackgroundWorker.CancelAsync(); if (winner != 0) ShowWinner(winner); } }; AIbackgroundWorker.RunWorkerCompleted += (sender, args) => { if (args.Error != null) // if an exception occurred during DoWork, { //Console.WriteLine("Something went wrong with AI thread."); MessageBox.Show(args.Error.ToString()); // do your error handling here } //Console.WriteLine("Good with AI thread."); int winner = gameBrain.CheckForWin(); if (winner == 0) { TranslateTransform translate = new TranslateTransform(); DoubleAnimation enter; Point targetPoint; //userMadeRotation = false; var element = gameBrain.GetComputerMove(); Rectangle rec = rectangleChildren.ElementAt(gameBrain.GetComputerMove()); targetPoint = rec.TranslatePoint(new Point(rec.ActualWidth, 0), Board); if (gameBrain.isPlayer1Turn()) { fireDragon = true; int computerRow = gameBrain.GetComputerMove() / 6; currentDragon = fireDragonEntryImages[computerRow]; currentDragon.RenderTransform = translate; currentDragon.Visibility = Visibility.Visible; enter = new DoubleAnimation(0, GetFireAnimationDestination(element, targetPoint), TimeSpan.FromSeconds(1)); } else { fireDragon = false; int computerRow = gameBrain.GetComputerMove() / 6; currentDragon = iceDragonEntryImages[computerRow]; currentDragon.RenderTransform = translate; currentDragon.Visibility = Visibility.Visible; enter = new DoubleAnimation(0, -GetIceAnimationDestination(element), TimeSpan.FromSeconds(1)); } enter.Completed += new EventHandler(OnAnimationEnterComputerCompletition); isAnimationEnterExecuting = true; translate.BeginAnimation(TranslateTransform.XProperty, enter); } else if (winner != 0) { RePaintBoard(); ShowWinner(winner); } }; AIbackgroundWorker.RunWorkerAsync(); }
/// <summary> /// Creates OgamaDataSet and fills it with data from SQL Databasefile /// given bei <see cref="Properties.ExperimentSettings.DatabaseConnectionString"/>. /// </summary> /// <param name="splash">The loading document splash screens background worker, /// needed for interrupting splash when SQL connection fails.</param> /// <returns><strong>True</strong>,if successful, otherwise /// <strong>false</strong>.</returns> public bool LoadSQLData(BackgroundWorker splash) { // Creates new DataSet this.dataSet = new SQLiteOgamaDataSet(); // Data Source=C:\Users\Adrian\Documents\OgamaExperiments\SlideshowDemo\Database\SlideshowDemo.sdf;Max Database Size=4091 //bool automaticCorrectMachineNameTried = false; //bool automaticResetConnectionTried = false; //bool logRebuild = false; if (!File.Exists(this.experimentSettings.DatabaseSQLiteFile)) { var result = InformationDialog.Show( "Upgrade Database", "We need to convert the SQL Database to SQLite. Otherwise Ogama will not be able to open the data. Please confirm the conversion process", true, MessageBoxIcon.Question); switch (result) { case DialogResult.Cancel: return false; case DialogResult.Yes: // Show loading splash screen if it is not running var bgwConvert = new BackgroundWorker(); bgwConvert.DoWork += this.bgwConvert_DoWork; bgwConvert.WorkerSupportsCancellation = true; bgwConvert.RunWorkerAsync(); // Remove the log, cause it may disable the conversion process // if it comes from another storage location if (File.Exists(this.experimentSettings.DatabaseLDFFile)) { File.Delete(this.experimentSettings.DatabaseLDFFile); } this.ConvertToSQLiteDatabase(); bgwConvert.CancelAsync(); InformationDialog.Show( "Conversion done.", "The database was converted to sqlite format. The original source was not removed.", false, MessageBoxIcon.Information); break; case DialogResult.No: break; } } // Check for existing database if (!File.Exists(this.experimentSettings.DatabaseSQLiteFile)) { string message = "The experiments database: " + Environment.NewLine + this.experimentSettings.DatabaseSQLiteFile + Environment.NewLine + "does not exist. This error could not be automically resolved." + Environment.NewLine + "Please move the database to the above location, " + "or create a new experiment."; ExceptionMethods.ProcessErrorMessage(message); return false; } // Show loading splash screen if it is not running if (splash != null && !splash.IsBusy) { splash.RunWorkerAsync(); } // SqlConnection connectionString = new SqlConnection(Document.ActiveDocument.ExperimentSettings.ServerConnectionString); // ServerConnection connection = new ServerConnection(connectionString); // Server sqlServer = new Server(connection); //Attach: // try // { // StringCollection sc = new StringCollection(); // sc.Add(Document.ActiveDocument.ExperimentSettings.DatabaseMDFFile); // if (logRebuild) // { // if (File.Exists(Document.ActiveDocument.ExperimentSettings.DatabaseLDFFile)) // { // File.Delete(Document.ActiveDocument.ExperimentSettings.DatabaseLDFFile); // } // } // else // { // sc.Add(Document.ActiveDocument.ExperimentSettings.DatabaseLDFFile); // } // // Attach database file // if (!sqlServer.Databases.Contains(Document.ActiveDocument.ExperimentSettings.Name)) // { // sqlServer.AttachDatabase( // Document.ActiveDocument.ExperimentSettings.Name, // sc, // logRebuild ? AttachOptions.RebuildLog : AttachOptions.None); // } // sqlServer.ConnectionContext.Disconnect(); // logRebuild = false; // } // catch (Exception ex) // { // // Check for the SQLError 9004, which indicates a failure // // in the log file, which can be fixed by rebuilding the log. // if (ex.InnerException != null) // { // if (ex.InnerException.InnerException != null) // { // if (ex.InnerException.InnerException is SqlException) // { // if (((SqlException)ex.InnerException.InnerException).Number == 9004) // { // logRebuild = true; // } // } // } // } // if (!logRebuild) // { // string message = @"The following error occured: " + ex.Message + Environment.NewLine + Environment.NewLine + // @"If it is the following: 'Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.'" + // @"Please delete the folder 'Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\" + Document.ActiveDocument.ExperimentSettings.SqlInstanceName + // "' in WinXP or " + // @"'AppData\Local\Microsoft\Microsoft SQL Server Data\" + Document.ActiveDocument.ExperimentSettings.SqlInstanceName + "' on Vista and Windows 7 and try again."; // ExceptionMethods.ProcessMessage("SQL Server connection failed.", message); // ExceptionMethods.ProcessUnhandledException(ex); // if (splash != null && splash.IsBusy) // { // splash.CancelAsync(); // } // return false; // } // } // // Go back and rebuild the log file. // if (logRebuild) // { // goto Attach; // } // Test connection using (var conn = new SQLiteConnection(Document.ActiveDocument.ExperimentSettings.DatabaseConnectionString)) { try { conn.Open(); } catch (Exception ex) { //if (splash != null && splash.IsBusy) //{ // splash.CancelAsync(); //} //if (!automaticResetConnectionTried) //{ // this.experimentSettings.CustomConnectionString = string.Empty; // this.isModified = true; // automaticResetConnectionTried = true; // goto Test; //} //if (!automaticCorrectMachineNameTried) //{ // string currentConnectionString = this.experimentSettings.DatabaseConnectionString; // int firstEqualSign = currentConnectionString.IndexOf('=', 0); // int firstBackslash = currentConnectionString.IndexOf('\\', 0); // string machineName = currentConnectionString.Substring(firstEqualSign + 1, firstBackslash - firstEqualSign - 1); // string currentMachineName = Environment.MachineName; // currentConnectionString = currentConnectionString.Replace(machineName + "\\", currentMachineName + "\\"); // this.experimentSettings.CustomConnectionString = currentConnectionString; // automaticCorrectMachineNameTried = true; // this.isModified = true; // goto Test; //} string message = "Connection to SQLite database failed." + Environment.NewLine + "Take a careful look at the database file to attach and its path. " + "The .db file should be named the same as the experiment .oga file and located in the " + "Database subfolder of the experiment." + Environment.NewLine + "The error message is: " + Environment.NewLine + ex.Message + Environment.NewLine; ExceptionMethods.ProcessErrorMessage(message); //SQLConnectionDialog connectionDialog = new SQLConnectionDialog(); //connectionDialog.ConnectionString = this.experimentSettings.DatabaseConnectionString; //if (connectionDialog.ShowDialog() == DialogResult.OK) //{ // this.experimentSettings.CustomConnectionString = connectionDialog.ConnectionString; // this.isModified = true; //} //else //{ // return false; //} //goto Test; } finally { try { conn.Close(); } catch (Exception) { } } } if (splash != null && !splash.IsBusy) { splash.RunWorkerAsync(); } Application.DoEvents(); // Loads tables and Data from SQL file into DataSet if (this.dataSet.LoadData(splash)) { return true; } return false; }