Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. public partial class AsyncProgressCancelExampleForm : Form
  2. {
  3. public AsyncProgressCancelExampleForm()
  4. {
  5. InitializeComponent();
  6. }
  7.  
  8. CancellationTokenSource _cts = new CancellationTokenSource();
  9.  
  10. private async void btnRunAsync_Click(object sender, EventArgs e)
  11. {
  12. //Instantiate progress indicator.
  13. //In this example we report <int> as progress, but
  14. //we could actually report a complex object providing more
  15. //information such as current operation, ETA, etc.
  16. var progressIndicator = new Progress<int>(ReportProgress);
  17. try
  18. {
  19. //Call our async method, pass progress indicator
  20. //and cancellation token as parameters
  21. await AsyncMethod(progressIndicator, _cts.Token);
  22. }
  23. catch (OperationCanceledException ex)
  24. {
  25. //Handle cancellation
  26. lblProgress.Text = "Cancelled";
  27. }
  28. }
  29.  
  30. private void btnCancel_Click(object sender, EventArgs e)
  31. {
  32. //Invoke cancellation
  33. _cts.Cancel();
  34. }
  35.  
  36. private void ReportProgress(int value)
  37. {
  38. //Print progress in a label
  39. lblProgress.Text = value.ToString();
  40. }
  41.  
  42. private async Task AsyncMethod(IProgress<int> progress, CancellationToken ct)
  43. {
  44. for (int i = 0; i < 100; i++)
  45. {
  46. //Simulate an async call that takes some time to complete
  47. await Task.Delay(1000);
  48.  
  49. //Check if cancellation has been requested
  50. if (ct != null)
  51. {
  52. ct.ThrowIfCancellationRequested();
  53. }
  54.  
  55. //Report progress
  56. if (progress != null)
  57. {
  58. progress.Report(i);
  59. }
  60. }
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement