/// <summary> /// Run a long running task composed of small awaited and configured tasks /// Using ConfigureAwait(false) makes this particular method run a bit faster /// then the example above. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ProcessAsync2Button_Click(object sender, EventArgs e) { if (_cancellationTokenSource.IsCancellationRequested) { _cancellationTokenSource.Dispose(); _cancellationTokenSource = new CancellationTokenSource(); } var ops = new Examples(); ops.OnIterate += Ops_OnIterate2; try { var result = await ops.ProcessAsync2(1000, _cancellationTokenSource.Token); Console.WriteLine(result); } catch (OperationCanceledException) { MessageBox.Show("Cancelled"); } catch (Exception exception) { MessageBox.Show($"Operation failed with\n{exception.Message}"); } }
/// <summary> /// User interface will not be responsive on the average machince /// The bottleneck is opening Excel for the first time /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ExcelSynchronousButton_Click(object sender, EventArgs e) { var excelFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MyFile.xlsx"); if (!File.Exists(excelFile)) { MessageBox.Show("Failed to find file, please ensure the file exists."); return; } var ops = new Examples(); ops.OpenExcel(excelFile, "Sheet2"); MessageBox.Show("Done. Check Task Manager Processes and Excel should not be in the list."); }
/// <summary> /// Allow the user interface to remain responsive. /// The bottleneck is opening Excel for the first time /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ExcelAsynchronousButton_Click(object sender, EventArgs e) { var excelFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MyFile.xlsx"); if (!File.Exists(excelFile)) { MessageBox.Show("Failed to find file, please ensure the file exists."); return; } var ops = new Examples(); try { await Task.Run(() => ops.OpenExcel(excelFile, "Sheet2")); } catch (Exception ex) { MessageBox.Show($"Encountered errors\n{ex.Message}"); } MessageBox.Show("Done"); }