using
System;
using
System.Collections.Generic;
using
System.Threading.Tasks;
using
System.Windows;
using
System.Net.Http;
using
System.Threading;
namespace
CancelATask
{
public
partial
class
MainWindow : Window
{
List<CancellationTokenSource> cts =
new
List<CancellationTokenSource>();
public
MainWindow()
{
InitializeComponent();
}
private
async
void
startButton_Click(
object
sender, RoutedEventArgs e)
{
cts?.ForEach(c => c.Cancel());
using
(CancellationTokenSource c =
new
CancellationTokenSource())
{
cts.Add(c);
try
{
int
contentLength = await AccessTheWebAsync(c.Token);
resultsTextBox.Text += $
"\r\nLength of the downloaded string: {contentLength}.\r\n"
;
}
catch
(OperationCanceledException)
{
resultsTextBox.Text += $
"\r\nDownload canceled. Current no of jobs: {cts.Count}\r\n"
;
}
catch
(Exception)
{
resultsTextBox.Text +=
"\r\nDownload failed.\r\n"
;
}
cts.Remove(c);
}
}
private
void
cancelButton_Click(
object
sender, RoutedEventArgs e)
{
cts?.ForEach(c => c.Cancel());
}
private
void
clearButton_Click(
object
sender, RoutedEventArgs e)
{
cts?.ForEach(c => c.Cancel());
resultsTextBox.Clear();
}
async Task<
int
> AccessTheWebAsync(CancellationToken c)
{
HttpClient client =
new
HttpClient();
resultsTextBox.Text +=
"Waiting for download to commence.\r\n"
;
await Task.Delay(5000, c);
resultsTextBox.Text +=
"Commencing to download.\r\n"
;
byte
[] urlContents = await response.Content.ReadAsByteArrayAsync();
return
urlContents.Length;
}
}
}