我正在尝试使用asp:fileupload上传多个文件(C#,asp.net),并且我希望此过程在单独的线程上执行,并且能够通过单击“取消”按钮来停止该过程,因此我创建了新任务我确实在单独的线程上执行,但是当我将此行放入取消代码tokenSource.Cancel()时, 如果(tokenSource。IsCancellationRequested)仍然为false,则该过程将持续到结束且不会停止,这是代码:
>
private CancellationTokenSource tokenSource= new CancellationTokenSource();
private CancellationToken token;
protected void submitupload_Click(object sender, EventArgs e)
{
fileCollection = Request.Files;
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes" && Selected_folder_name.SelectedIndex > 0)
{
if (FileUpload.HasFile)
{
tokenSource = new CancellationTokenSource();
token = tokenSource.Token;
Task.Factory.StartNew(() =>
{
int count = 0;
while (!tokenSource.Token.IsCancellationRequested &&
count<fileCollection.Count)
{
HttpPostedFile uploadfile = fileCollection[count];
String fileName = Path.GetFileName(uploadfile.FileName);
string fileExxtension = Path.GetExtension(uploadfile.FileName);
uploadfile.SaveAs(Chosen_Site_Path + @"\"
+Selected_folder_name.SelectedItem.Text + @"\" + fileName);
count++;
}
}, token);
}
}
}
protected void cancelupload_Click(object sender, EventArgs e)
{
tokenSource.Cancel();
}