フィルターと 2 つのボタン (生成とキャンセル) を含むページがあります。そのため、Generate ボタンをクリックすると、Results アクションに移動します。[キャンセル] ボタンをクリックすると、コードとデータベースで以前のリクエストをキャンセルしたいと思います。
いくつかのコード (.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() メソッドを使用する必要があります (どこで?)