【发布时间】:2017-09-27 21:17:11
【问题描述】:
在我看来,我有两个按钮,一个调用 Start() 操作,一个调用 Stop()。这是控制器的外观:
public class TestController : AsyncController
{
public static CancellationTokenSource cts = new CancellationTokenSource();
public void StartAsync()
{
cts = new CancellationTokenSource();
CancellationToken cancellationToken = cts.Token;
AsyncManager.OutstandingOperations.Increment();
AsyncManager.Parameters["task"] = Task.Factory.StartNew(() =>
{
try
{
while() {
if (cancellationToken.IsCancellationRequested)
break;
// Do stuff
}
}
finally
{
AsyncManager.OutstandingOperations.Decrement();
}
}, cancellationToken);
}
public ActionResult StartCompleted(Task task)
{
try
{
task.Wait();
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
}
public void StopAsync()
{
cts.Cancel();
}
public ActionResult StopCompleted()
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
但是当我单击停止按钮时,只有在开始完成后才会调用停止操作。我应该如何停止操作?
【问题讨论】:
标签: c# asp.net-mvc asynchronous