我正在尝试获取在Mvc中处理的Ajax请求的百分比。我了解到,这应该使用AsyncController完成。 但是当第一个请求成功时,我没有得到百分比,因为它在 TaskProgress 尾巴上。
控制器:
public class AsyncTestController : AsyncController
{
public void TaskAsync(int id)
{
AsyncManager.OutstandingOperations.Increment();
Task.Factory.StartNew(taskId =>
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(200);
HttpContext.Application["task" + taskId] = i;
}
var result = "result";
AsyncManager.OutstandingOperations.Decrement();
AsyncManager.Parameters["result"] = result;
return result;
}, id);
}
public ActionResult TaskCompleted(string result)
{
return Content(result, "text/plain");
}
public ActionResult TaskProgress(int id)
{
string asd = HttpContext.Application["task" + id].ToString();
return Json(new
{
Progress = HttpContext.Application["task" + id]
}, JsonRequestBehavior.AllowGet);
}
}
查看(javascript):
function async_test_start() {
var taskId = 543;
$.ajax({
url: '@Url.Content("~/IK/AsyncTest/task/")',
data: { id: taskId },
type: "GET",
async: true,
success: function (dt) {
window.clearInterval(intervalId);
console.log(dt);
}
});
var intervalId = window.setInterval(function () {
$.ajax({
url: '@Url.Content("~/IK/AsyncTest/taskprogress/")',
data: { id: taskId },
type: "GET",
async: true,
success: function (dt) {
console.log(dt.Progress + '%');
}
});
}, 5000);
}
结果(当ajax请求开始时):