我有一个带过滤器和2个按钮的页面:生成和取消。所以,当我点击Generate按钮时,我会转到Results action。当我点击取消按钮时,我想取消之前在代码和数据库中的请求。
一些代码(我使用的是.NET 4.0,MVC 4)
ResultsController.cs:
public Task<PartialViewResult> Results(int id)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
System.Web.HttpContext.Current.Application.Add("token", tokenSource);
Task<PartialViewResult> task = Task.Factory.StartNew(() => {
return ResultsRepository.PrepareViewModel(id);
}, tokenSource.Token).ContinueWith(x => PartialView("Results", x.Result), TaskContinuationOptions.OnlyOnRanToCompletion);
System.Web.HttpContext.Current.Application.Add("task", task);
return task;
}
public JsonResult CancelResultsByMonthGeneration(int id, DateTime selectedMonth)
{
CancellationTokenSource tokenSource = System.Web.HttpContext.Current.Application["token"] as CancellationTokenSource;
Task<PartialViewResult> task = System.Web.HttpContext.Current.Application["task"] as Task<PartialViewResult>;
try {
if (tokenSource != null) {
tokenSource.Cancel();
task.Wait();
}
}
finally {
task.Dispose();
tokenSource.Dispose();
}
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
ResultsRepository.cs
public ResultsViewModel PrepareViewModel(int id)
{
// use Entity Framework to call stored procedure
}
因此,预期结果:如果我取消报告生成请求应该被取消,则不会显示任何数据。
主要问题:我可以使用方法tokenSource.Cancel()取消请求吗? 或者我应该使用ThrowIfCancellationRequested()方法(在哪里?)