Cra*_*aig 8 c# asp.net asp.net-mvc-4
我正在使用MVC 4中新的Async Controller功能,如下所述http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4
如果我有一个可能需要10-20秒才能运行的操作,我想提供某种状态栏来通知用户进度.Async功能有什么可以帮助解决这个问题吗?
编辑:我将尝试如何尝试并看看是否有更好的方法
public async Task<ActionResult> GizmosAsync()
{
return View("Gizmos", await GetGizmosAsync());
}
private void GetGizmosAsync()
{
for(int i=0; i<10; i++)
{
lock(_locker)
{
_statusMessage = String.Format("{0} of 10", i);
}
DoSomethingLongRunning();
}
}
public ActionResult Status()
{
return Json(new { Status = _statusMessage });
}
static readonly object _locker = new object();
static string _statusMessage = "";
....
<script>
setTimeout(displayStatus, 1000);
function displayStatus() {
$.post("/controller/status", function(data) {
alert(data.Status);
});
}
</script>
Run Code Online (Sandbox Code Playgroud)
Pab*_*meo 15
异步控制器只是一种从IIS中的ThreadPool中释放线程的机制,以便能够在繁重负载期间处理传入请求,但与客户端的通信仍然是通常的请求 - 响应.
状态栏和排序通常只是javascript在屏幕上显示某些内容,直到ajax请求完成.我认为MVC4不会对那部分有帮助.
你可以这样做:https://stackoverflow.com/a/68503/1373170<div>在ajax调用期间显示"处理..." .
编辑:如果您需要真正的客户端进度和交互(例如实际进度),您应该查看SignalR http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx 和这个相关的帖子:异步控制器(MVC),长时间运行进程"停止"
这篇文章似乎描述了你想要的:
ASP.NET MVC 3:用于长时间运行任务的异步jQuery进度指示器
控制器:
public class HomeController : Controller
{
private static IDictionary<Guid, int> tasks = new Dictionary<Guid, int>();
public ActionResult Index()
{
return View();
}
public ActionResult Start()
{
var taskId = Guid.NewGuid();
tasks.Add(taskId, 0);
Task.Factory.StartNew(() =>
{
for (var i = 0; i <= 100; i++)
{
tasks[taskId] = i; // update task progress
Thread.Sleep(50); // simulate long running operation
}
tasks.Remove(taskId);
});
return Json(taskId);
}
public ActionResult Progress(Guid id)
{
return Json(tasks.Keys.Contains(id) ? tasks[id] : 100);
}
}
Run Code Online (Sandbox Code Playgroud)
视图:
<script type="text/javascript">
function updateMonitor(taskId, status) {
$("#" + taskId).html("Task [" + taskId + "]: " + status);
}
$(function () {
$("#start").click(function (e) {
e.preventDefault();
$.post("Home/Start", {}, function (taskId) {
// Init monitors
$("#monitors").append($("<p id='" + taskId + "'/>"));
updateMonitor(taskId, "Started");
// Periodically update monitors
var intervalId = setInterval(function () {
$.post("Home/Progress", { id: taskId }, function (progress) {
if (progress >= 100) {
updateMonitor(taskId, "Completed");
clearInterval(intervalId);
} else {
updateMonitor(taskId, progress + "%");
}
});
}, 100);
});
});
});
</script>
<div id="monitors"></div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23454 次 |
| 最近记录: |