gpt4 book ai didi

c# - ASP.NET MVC 4 异步 Controller 回调

转载 作者:太空狗 更新时间:2023-10-29 18:08:35 26 4
gpt4 key购买 nike

我只是按照此处所述使用 MVC 4 中的新异步 Controller 功能 http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4

如果我有一个可能需要 10-20 秒才能运行的操作,我想提供某种状态栏来通知用户进度。异步功能是否可以帮助解决这个问题?

编辑:我将试一试我将如何尝试去做,看看是否有更好的方法

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>

最佳答案

异步 Controller 只是一种从 IIS 中的 ThreadPool 中释放线程的机制,以便能够在重负载期间处理传入的请求,但与客户端的通信仍然是通常的请求-响应。

状态栏和排序通常只是 javascript 在屏幕上显示一些东西,直到 ajax 请求完成。我认为 MVC4 不会在这方面提供帮助。

你可以这样做:https://stackoverflow.com/a/68503/1373170显示“正在处理...”<div>在 ajax 调用期间。

编辑:如果您需要真实的客户端进度和交互(例如真实进度),您应该查看SignalR http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx和这个相关的帖子:Async Controllers (MVC), long running process with "stops"

关于c# - ASP.NET MVC 4 异步 Controller 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11337770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com