取消一項非同步工作或工作清單 (C# 和 Visual Basic)
如果不想等待非同步應用程式完成,可以設定能用於取消該應用程式的按鈕。 依照本主題中的範例,您可以將取消按鈕加入至下載一個網站或清單所列網站之內容的應用程式。
範例會使用 微調非同步應用程式 (C# 和 Visual Basic) 描述的 UI。
注意事項 |
---|
若要執行範例,您必須將 Visual Studio 2012、Visual Studio 2013、Visual Studio Express 2012 for Windows Desktop、Visual Studio Express 2013 for Windows 或 .NET Framework 4.5 或 4.5.1 安裝在您的電腦上。 |
取消工作
第一個範例會將 [取消] 按鈕與單一下載工作產生關聯。 如果您在應用程式下載內容時選取此按鈕,則會取消下載。
下載範例
您可以從非同步範例:微調應用程式下載完整的 Windows Presentation Foundation (WPF) 專案,然後依照下列步驟執行。
解壓縮您下載的檔案,然後啟動 Visual Studio。
在功能表列上,選擇 [檔案]、[開啟]、[專案/方案]。
在 [開啟專案] 對話方塊中,開啟含有已解壓縮之範例程式碼的資料夾,然後開啟 AsyncFineTuningCS 或 AsyncFineTuningVB 的方案 (.sln) 檔。
在 [方案總管] 中,開啟 [CancelATask] 專案的捷徑功能表,然後選取 [設定為啟始專案]。
選擇 F5 鍵以執行專案。
選取 Ctrl+F5 鍵執行專案,但不偵錯。
如果您不要下載專案,您可以檢視本主題結尾的 MainWindow.xaml.vb 和 MainWindow.xaml.cs 檔案。
建置範例
下列變更將 [取消] 按鈕加入至下載網站的應用程式。 如果您不要下載或建置這個範例,您可以檢閱本主題結尾<完整範例>一節中的最終產品。 星號標示出程式碼中的變更。
若要建置範例,請依照<下載範例>中的指示逐步執行,不過選擇 StarterCode 為 [啟始專案],而不選擇 CancelATask。
然後將下列變更加入至該專案的 MainWindow.xaml.vb 或 MainWindow.xaml.cs 檔案中。
宣告 CancellationTokenSource 變數 cts,也就是在所有存取此變數之方法的範圍中宣告。
Class MainWindow ' ***Declare a System.Threading.CancellationTokenSource. Dim cts As CancellationTokenSource
public partial class MainWindow : Window { // ***Declare a System.Threading.CancellationTokenSource. CancellationTokenSource cts;
為 [取消] 按鈕加入下列事件處理常式。 當使用者要求取消時,事件處理常式會使用 CancellationTokenSource.Cancel 方法通知 cts。
' ***Add an event handler for the Cancel button. Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs) If cts IsNot Nothing Then cts.Cancel() End If End Sub
// ***Add an event handler for the Cancel button. private void cancelButton_Click(object sender, RoutedEventArgs e) { if (cts != null) { cts.Cancel(); } }
在 [開始] 按鈕 startButton_Click 的事件處理常式中進行下列變更。
具現化 CancellationTokenSource,cts。
' ***Instantiate the CancellationTokenSource. cts = New CancellationTokenSource()
// ***Instantiate the CancellationTokenSource. cts = new CancellationTokenSource();
在 AccessTheWebAsync 呼叫中 (用於下載指定網站的內容),傳送 cts 的 CancellationTokenSource.Token 屬性做為引數。 如果要求取消, Token 屬性會傳播訊息。 加入如果使用者選擇取消下載作業時,將會顯示訊息的 catch 區塊。 下列程式碼顯示變更。
Try ' ***Send a token to carry the message if cancellation is requested. Dim contentLength As Integer = Await AccessTheWebAsync(cts.Token) resultsTextBox.Text &= String.Format(vbCrLf & "Length of the downloaded string: {0}." & vbCrLf, contentLength) ' *** If cancellation is requested, an OperationCanceledException results. Catch ex As OperationCanceledException resultsTextBox.Text &= vbCrLf & "Download canceled." & vbCrLf Catch ex As Exception resultsTextBox.Text &= vbCrLf & "Download failed." & vbCrLf End Try
try { // ***Send a token to carry the message if cancellation is requested. int contentLength = await AccessTheWebAsync(cts.Token); resultsTextBox.Text += String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength); } // *** If cancellation is requested, an OperationCanceledException results. catch (OperationCanceledException) { resultsTextBox.Text += "\r\nDownload canceled.\r\n"; } catch (Exception) { resultsTextBox.Text += "\r\nDownload failed.\r\n"; }
在 AccessTheWebAsync,請使用 HttpClient 類型之 GetAsync 方法的 HttpClient.GetAsync(String, CancellationToken) 多載來下載網站的內容。 傳遞 ct (AccessTheWebAsync 的 CancellationToken 參數) 做為第二個引數。 如果使用者選擇 [取消] 按鈕,此語彙基元會傳送訊息。
下列程式碼顯示在 AccessTheWebAsync 中的變更。
' ***Provide a parameter for the CancellationToken. Async Function AccessTheWebAsync(ct As CancellationToken) As Task(Of Integer) Dim client As HttpClient = New HttpClient() resultsTextBox.Text &= String.Format(vbCrLf & "Ready to download." & vbCrLf) ' You might need to slow things down to have a chance to cancel. Await Task.Delay(250) ' GetAsync returns a Task(Of HttpResponseMessage). ' ***The ct argument carries the message if the Cancel button is chosen. Dim response As HttpResponseMessage = Await client.GetAsync("https://msdn.microsoft.com/en-us/library/dd470362.aspx", ct) ' Retrieve the website contents from the HttpResponseMessage. Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync() ' The result of the method is the length of the downloaded website. Return urlContents.Length End Function
// ***Provide a parameter for the CancellationToken. async Task<int> AccessTheWebAsync(CancellationToken ct) { HttpClient client = new HttpClient(); resultsTextBox.Text += String.Format("\r\nReady to download.\r\n"); // You might need to slow things down to have a chance to cancel. await Task.Delay(250); // GetAsync returns a Task<HttpResponseMessage>. // ***The ct argument carries the message if the Cancel button is chosen. HttpResponseMessage response = await client.GetAsync("https://msdn.microsoft.com/en-us/library/dd470362.aspx", ct); // Retrieve the website contents from the HttpResponseMessage. byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); // The result of the method is the length of the downloaded website. return urlContents.Length; }
如果您無法取消,程式會產生下列輸出。
Ready to download. Length of the downloaded string: 158125.
如果您在程式完成下載內容之前選取 [取消] 按鈕,程式會產生下列輸出。
Ready to download. Download canceled.
取消工作的清單。
您可以擴充前一個範例,藉由關聯同樣的 CancellationTokenSource 與每一個工作來取消執行許多工作。 如果您選取 [取消] 按鈕,您會取消所有未完成的工作。
下載範例
您可以從非同步範例:微調應用程式下載完整的 Windows Presentation Foundation (WPF) 專案,然後依照下列步驟執行。
解壓縮您下載的檔案,然後啟動 Visual Studio 2012。
在功能表列上,選擇 [檔案]、[開啟]、[專案/方案]。
在 [開啟專案] 對話方塊中,開啟含有已解壓縮之範例程式碼的資料夾,然後開啟 AsyncFineTuningCS 或 AsyncFineTuningVB 的方案 (.sln) 檔。
在 [方案總管] 中,開啟 [CancelAListOfTasks] 專案的捷徑功能表,然後選取 [設定為啟始專案]。
選擇 F5 鍵以執行專案。
選取 Ctrl+F5 鍵執行專案,但不偵錯。
如果您不要下載專案,您可以檢視本主題結尾的 MainWindow.xaml.vb 和 MainWindow.xaml.cs 檔案。
建置範例
若要擴充範例,請依照<下載範例>中的指示逐步執行,不過選取 CancelATask 為 [啟始專案]。 將下列變更加入至該專案。 星號標示出程式中的變更。
加入方法以建立網路位址清單。
' ***Add a method that creates a list of web addresses. Private Function SetUpURLList() As List(Of String) Dim urls = New List(Of String) From { "https://msdn.microsoft.com", "https://msdn.microsoft.com/en-us/library/hh290138.aspx", "https://msdn.microsoft.com/en-us/library/hh290140.aspx", "https://msdn.microsoft.com/en-us/library/dd470362.aspx", "https://msdn.microsoft.com/en-us/library/aa578028.aspx", "https://msdn.microsoft.com/en-us/library/ms404677.aspx", "https://msdn.microsoft.com/en-us/library/ff730837.aspx" } Return urls End Function
// ***Add a method that creates a list of web addresses. private List<string> SetUpURLList() { List<string> urls = new List<string> { "https://msdn.microsoft.com", "https://msdn.microsoft.com/en-us/library/hh290138.aspx", "https://msdn.microsoft.com/en-us/library/hh290140.aspx", "https://msdn.microsoft.com/en-us/library/dd470362.aspx", "https://msdn.microsoft.com/en-us/library/aa578028.aspx", "https://msdn.microsoft.com/en-us/library/ms404677.aspx", "https://msdn.microsoft.com/en-us/library/ff730837.aspx" }; return urls; }
呼叫 AccessTheWebAsync 中的方法。
' ***Call SetUpURLList to make a list of web addresses. Dim urlList As List(Of String) = SetUpURLList()
// ***Call SetUpURLList to make a list of web addresses. List<string> urlList = SetUpURLList();
在 AccessTheWebAsync 中加入下列迴圈以處理清單中的每個網路位址。
' ***Add a loop to process the list of web addresses. For Each url In urlList ' GetAsync returns a Task(Of HttpResponseMessage). ' Argument ct carries the message if the Cancel button is chosen. ' ***Note that the Cancel button can cancel all remaining downloads. Dim response As HttpResponseMessage = Await client.GetAsync(url, ct) ' Retrieve the website contents from the HttpResponseMessage. Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync() resultsTextBox.Text &= String.Format(vbCrLf & "Length of the downloaded string: {0}." & vbCrLf, urlContents.Length) Next
// ***Add a loop to process the list of web addresses. foreach (var url in urlList) { // GetAsync returns a Task<HttpResponseMessage>. // Argument ct carries the message if the Cancel button is chosen. // ***Note that the Cancel button can cancel all remaining downloads. HttpResponseMessage response = await client.GetAsync(url, ct); // Retrieve the website contents from the HttpResponseMessage. byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); resultsTextBox.Text += String.Format("\r\nLength of the downloaded string: {0}.\r\n", urlContents.Length); }
由於 AccessTheWebAsync 會顯示長度,方法不需傳回任何值。 移除 return 陳述式,並且將方法的傳回類型變更為 Task,而不是 Task。
Async Function AccessTheWebAsync(ct As CancellationToken) As Task
async Task AccessTheWebAsync(CancellationToken ct)
使用陳述式 (而不是運算式),從 startButton_Click 呼叫方法。
Await AccessTheWebAsync(cts.Token)
await AccessTheWebAsync(cts.Token);
如果您無法取消,程式會產生下列輸出。
Length of the downloaded string: 35939. Length of the downloaded string: 237682. Length of the downloaded string: 128607. Length of the downloaded string: 158124. Length of the downloaded string: 204890. Length of the downloaded string: 175488. Length of the downloaded string: 145790. Downloads complete.
如果您在下載完成之前選取 [取消] 按鈕,輸出包含在取消之前完成下載的長度。
Length of the downloaded string: 35939. Length of the downloaded string: 237682. Length of the downloaded string: 128607. Downloads canceled.
完整範例
下列章節包含先前每一個範例的程式碼。 請注意,您必須加入 System.Net.Http 的參考。
您可以從 Async 範例:微調應用程式 下載專案。
取消工作範例
下列程式碼是移除單一工作之範例的完整 MainWindow.xaml.vb 或 MainWindow.xaml.cs 檔案。
' Add an Imports directive and a reference for System.Net.Http.
Imports System.Net.Http
' Add the following Imports directive for System.Threading.
Imports System.Threading
Class MainWindow
' ***Declare a System.Threading.CancellationTokenSource.
Dim cts As CancellationTokenSource
Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs)
' ***Instantiate the CancellationTokenSource.
cts = New CancellationTokenSource()
resultsTextBox.Clear()
Try
' ***Send a token to carry the message if cancellation is requested.
Dim contentLength As Integer = Await AccessTheWebAsync(cts.Token)
resultsTextBox.Text &=
String.Format(vbCrLf & "Length of the downloaded string: {0}." & vbCrLf, contentLength)
' *** If cancellation is requested, an OperationCanceledException results.
Catch ex As OperationCanceledException
resultsTextBox.Text &= vbCrLf & "Download canceled." & vbCrLf
Catch ex As Exception
resultsTextBox.Text &= vbCrLf & "Download failed." & vbCrLf
End Try
' ***Set the CancellationTokenSource to Nothing when the download is complete.
cts = Nothing
End Sub
' ***Add an event handler for the Cancel button.
Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs)
If cts IsNot Nothing Then
cts.Cancel()
End If
End Sub
' ***Provide a parameter for the CancellationToken.
Async Function AccessTheWebAsync(ct As CancellationToken) As Task(Of Integer)
Dim client As HttpClient = New HttpClient()
resultsTextBox.Text &=
String.Format(vbCrLf & "Ready to download." & vbCrLf)
' You might need to slow things down to have a chance to cancel.
Await Task.Delay(250)
' GetAsync returns a Task(Of HttpResponseMessage).
' ***The ct argument carries the message if the Cancel button is chosen.
Dim response As HttpResponseMessage = Await client.GetAsync("https://msdn.microsoft.com/en-us/library/dd470362.aspx", ct)
' Retrieve the website contents from the HttpResponseMessage.
Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
' The result of the method is the length of the downloaded website.
Return urlContents.Length
End Function
End Class
' Output for a successful download:
' Ready to download.
' Length of the downloaded string: 158125.
' Or, if you cancel:
' Ready to download.
' Download canceled.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
// Add a using directive and a reference for System.Net.Http.
using System.Net.Http;
// Add the following using directive for System.Threading.
using System.Threading;
namespace CancelATask
{
public partial class MainWindow : Window
{
// ***Declare a System.Threading.CancellationTokenSource.
CancellationTokenSource cts;
public MainWindow()
{
InitializeComponent();
}
private async void startButton_Click(object sender, RoutedEventArgs e)
{
// ***Instantiate the CancellationTokenSource.
cts = new CancellationTokenSource();
resultsTextBox.Clear();
try
{
// ***Send a token to carry the message if cancellation is requested.
int contentLength = await AccessTheWebAsync(cts.Token);
resultsTextBox.Text +=
String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
}
// *** If cancellation is requested, an OperationCanceledException results.
catch (OperationCanceledException)
{
resultsTextBox.Text += "\r\nDownload canceled.\r\n";
}
catch (Exception)
{
resultsTextBox.Text += "\r\nDownload failed.\r\n";
}
// ***Set the CancellationTokenSource to null when the download is complete.
cts = null;
}
// ***Add an event handler for the Cancel button.
private void cancelButton_Click(object sender, RoutedEventArgs e)
{
if (cts != null)
{
cts.Cancel();
}
}
// ***Provide a parameter for the CancellationToken.
async Task<int> AccessTheWebAsync(CancellationToken ct)
{
HttpClient client = new HttpClient();
resultsTextBox.Text +=
String.Format("\r\nReady to download.\r\n");
// You might need to slow things down to have a chance to cancel.
await Task.Delay(250);
// GetAsync returns a Task<HttpResponseMessage>.
// ***The ct argument carries the message if the Cancel button is chosen.
HttpResponseMessage response = await client.GetAsync("https://msdn.microsoft.com/en-us/library/dd470362.aspx", ct);
// Retrieve the website contents from the HttpResponseMessage.
byte[] urlContents = await response.Content.ReadAsByteArrayAsync();
// The result of the method is the length of the downloaded website.
return urlContents.Length;
}
}
// Output for a successful download:
// Ready to download.
// Length of the downloaded string: 158125.
// Or, if you cancel:
// Ready to download.
// Download canceled.
}
取消工作清單範例
下列程式碼是移除工作清單之範例的完整 MainWindow.xaml.vb 或 MainWindow.xaml.cs 檔案。
' Add an Imports directive and a reference for System.Net.Http.
Imports System.Net.Http
' Add the following Imports directive for System.Threading.
Imports System.Threading
Class MainWindow
' Declare a System.Threading.CancellationTokenSource.
Dim cts As CancellationTokenSource
Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs)
' Instantiate the CancellationTokenSource.
cts = New CancellationTokenSource()
resultsTextBox.Clear()
Try
' ***AccessTheWebAsync returns a Task, not a Task(Of Integer).
Await AccessTheWebAsync(cts.Token)
' ***Small change in the display lines.
resultsTextBox.Text &= vbCrLf & "Downloads complete."
Catch ex As OperationCanceledException
resultsTextBox.Text &= vbCrLf & "Downloads canceled." & vbCrLf
Catch ex As Exception
resultsTextBox.Text &= vbCrLf & "Downloads failed." & vbCrLf
End Try
' Set the CancellationTokenSource to Nothing when the download is complete.
cts = Nothing
End Sub
' Add an event handler for the Cancel button.
Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs)
If cts IsNot Nothing Then
cts.Cancel()
End If
End Sub
' Provide a parameter for the CancellationToken.
' ***Change the return type to Task because the method has no return statement.
Async Function AccessTheWebAsync(ct As CancellationToken) As Task
Dim client As HttpClient = New HttpClient()
' ***Call SetUpURLList to make a list of web addresses.
Dim urlList As List(Of String) = SetUpURLList()
' ***Add a loop to process the list of web addresses.
For Each url In urlList
' GetAsync returns a Task(Of HttpResponseMessage).
' Argument ct carries the message if the Cancel button is chosen.
' ***Note that the Cancel button can cancel all remaining downloads.
Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)
' Retrieve the website contents from the HttpResponseMessage.
Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
resultsTextBox.Text &=
String.Format(vbCrLf & "Length of the downloaded string: {0}." & vbCrLf, urlContents.Length)
Next
End Function
' ***Add a method that creates a list of web addresses.
Private Function SetUpURLList() As List(Of String)
Dim urls = New List(Of String) From
{
"https://msdn.microsoft.com",
"https://msdn.microsoft.com/en-us/library/hh290138.aspx",
"https://msdn.microsoft.com/en-us/library/hh290140.aspx",
"https://msdn.microsoft.com/en-us/library/dd470362.aspx",
"https://msdn.microsoft.com/en-us/library/aa578028.aspx",
"https://msdn.microsoft.com/en-us/library/ms404677.aspx",
"https://msdn.microsoft.com/en-us/library/ff730837.aspx"
}
Return urls
End Function
End Class
' Output if you do not choose to cancel:
' Length of the downloaded string: 35939.
' Length of the downloaded string: 237682.
' Length of the downloaded string: 128607.
' Length of the downloaded string: 158124.
' Length of the downloaded string: 204890.
' Length of the downloaded string: 175488.
' Length of the downloaded string: 145790.
' Downloads complete.
' Sample output if you choose to cancel:
' Length of the downloaded string: 35939.
' Length of the downloaded string: 237682.
' Length of the downloaded string: 128607.
' Downloads canceled.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
// Add a using directive and a reference for System.Net.Http.
using System.Net.Http;
// Add the following using directive for System.Threading.
using System.Threading;
namespace CancelAListOfTasks
{
public partial class MainWindow : Window
{
// Declare a System.Threading.CancellationTokenSource.
CancellationTokenSource cts;
public MainWindow()
{
InitializeComponent();
}
private async void startButton_Click(object sender, RoutedEventArgs e)
{
// Instantiate the CancellationTokenSource.
cts = new CancellationTokenSource();
resultsTextBox.Clear();
try
{
await AccessTheWebAsync(cts.Token);
// ***Small change in the display lines.
resultsTextBox.Text += "\r\nDownloads complete.";
}
catch (OperationCanceledException)
{
resultsTextBox.Text += "\r\nDownloads canceled.";
}
catch (Exception)
{
resultsTextBox.Text += "\r\nDownloads failed.";
}
// Set the CancellationTokenSource to null when the download is complete.
cts = null;
}
// Add an event handler for the Cancel button.
private void cancelButton_Click(object sender, RoutedEventArgs e)
{
if (cts != null)
{
cts.Cancel();
}
}
// Provide a parameter for the CancellationToken.
// ***Change the return type to Task because the method has no return statement.
async Task AccessTheWebAsync(CancellationToken ct)
{
// Declare an HttpClient object.
HttpClient client = new HttpClient();
// ***Call SetUpURLList to make a list of web addresses.
List<string> urlList = SetUpURLList();
// ***Add a loop to process the list of web addresses.
foreach (var url in urlList)
{
// GetAsync returns a Task<HttpResponseMessage>.
// Argument ct carries the message if the Cancel button is chosen.
// ***Note that the Cancel button can cancel all remaining downloads.
HttpResponseMessage response = await client.GetAsync(url, ct);
// Retrieve the website contents from the HttpResponseMessage.
byte[] urlContents = await response.Content.ReadAsByteArrayAsync();
resultsTextBox.Text +=
String.Format("\r\nLength of the downloaded string: {0}.\r\n", urlContents.Length);
}
}
// ***Add a method that creates a list of web addresses.
private List<string> SetUpURLList()
{
List<string> urls = new List<string>
{
"https://msdn.microsoft.com",
"https://msdn.microsoft.com/en-us/library/hh290138.aspx",
"https://msdn.microsoft.com/en-us/library/hh290140.aspx",
"https://msdn.microsoft.com/en-us/library/dd470362.aspx",
"https://msdn.microsoft.com/en-us/library/aa578028.aspx",
"https://msdn.microsoft.com/en-us/library/ms404677.aspx",
"https://msdn.microsoft.com/en-us/library/ff730837.aspx"
};
return urls;
}
}
// Output if you do not choose to cancel:
//Length of the downloaded string: 35939.
//Length of the downloaded string: 237682.
//Length of the downloaded string: 128607.
//Length of the downloaded string: 158124.
//Length of the downloaded string: 204890.
//Length of the downloaded string: 175488.
//Length of the downloaded string: 145790.
//Downloads complete.
// Sample output if you choose to cancel:
//Length of the downloaded string: 35939.
//Length of the downloaded string: 237682.
//Length of the downloaded string: 128607.
//Downloads canceled.
}
請參閱
參考
概念
使用 Async 和 Await 設計非同步程式 (C# 和 Visual Basic)