[英]Add cancellation token to an async task with progress
我使用下面的代碼在WPF頁面異步方式中執行耗時的操作以及向UI報告進度
private void btnStart_Click(object sender, RoutedEventArgs e)
{
txt_importStatus.Text = "";
var progress = new Progress<string>(progress_info =>
{
//show import progress on a textfield
txt_importStatus.Text = progress_info + Environment.NewLine + "Please dont close this window while the system processing the excel file contents";
});
// DoProcessing is run on the thread pool.
await Task.Run(() => DoProcessing(progress));
}
public void DoProcessing(IProgress<string> progress)
{
//read an excel file and foreach excel file row
foreach(excelrow row in excelrowlist)
{
//do db entry and update UI the progress like
progress.Report("Processed x number of records. please wait..");
}
}
現在我想添加一個額外的選項,在中間取消這個異步操作。為此我發現我必須添加以下選項
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
private void btnCacnel_Click(object sender, RoutedEventArgs e)
{
tokenSource.Cancel();
}
但是如何將此tokenSource傳遞給我的DoProcessing調用以及如何在DoProcessing中處理取消
你其實並不需要的傳遞CancellationTokenSource
到DoProcessing
,但只是CancellationToken
。
為了處理取消,您可以執行以下操作:
public void DoProcessing(CancellationToken token, IProgress<string> progress)
{
//read an excel file and foreach excel file row
foreach(excelrow row in excelrowlist)
{
if(token.IsCancellationRequested)
break;
//do db entry and update UI the progress like
progress.Report("Processed x number of records. please wait..");
}
}
在這種情況下,您需要在btnStart_Click
創建取消令牌源。 如果不清楚,你需要這樣做:
CancellationTokenSource tokenSource;
private void btnStart_Click(object sender, RoutedEventArgs e)
{
txt_importStatus.Text = "";
var progress = new Progress<string>(progress_info =>
{
//show import progress on a textfield
txt_importStatus.Text = progress_info + Environment.NewLine + "Please dont close this window while the system processing the excel file contents";
});
// DoProcessing is run on the thread pool.
tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
await Task.Run(() => DoProcessing(token, progress));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.