Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public partial class AsyncProgressCancelExampleForm : Form
- {
- public AsyncProgressCancelExampleForm()
- {
- InitializeComponent();
- }
- CancellationTokenSource _cts = new CancellationTokenSource();
- private async void btnRunAsync_Click(object sender, EventArgs e)
- {
- //Instantiate progress indicator.
- //In this example we report <int> as progress, but
- //we could actually report a complex object providing more
- //information such as current operation, ETA, etc.
- var progressIndicator = new Progress<int>(ReportProgress);
- try
- {
- //Call our async method, pass progress indicator
- //and cancellation token as parameters
- await AsyncMethod(progressIndicator, _cts.Token);
- }
- catch (OperationCanceledException ex)
- {
- //Handle cancellation
- lblProgress.Text = "Cancelled";
- }
- }
- private void btnCancel_Click(object sender, EventArgs e)
- {
- //Invoke cancellation
- _cts.Cancel();
- }
- private void ReportProgress(int value)
- {
- //Print progress in a label
- lblProgress.Text = value.ToString();
- }
- private async Task AsyncMethod(IProgress<int> progress, CancellationToken ct)
- {
- for (int i = 0; i < 100; i++)
- {
- //Simulate an async call that takes some time to complete
- await Task.Delay(1000);
- //Check if cancellation has been requested
- if (ct != null)
- {
- ct.ThrowIfCancellationRequested();
- }
- //Report progress
- if (progress != null)
- {
- progress.Report(i);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement