长时间运行时显示进度?

发布于 2024-10-09 05:25:04 字数 673 浏览 1 评论 0原文

在我的 ASP.NET MVC3 项目中,我有一个运行一定时间的操作。 如果它可以将部分响应发送回视图,那就太好了。 目标是向用户展示一些进度信息。 有人知道如何使其发挥作用吗?

我尝试了一些直接输出到响应,但它不是部分发送给客户端,而是全部发送到一个块:

[HttpPost]
public string DoTimeConsumingThings(int someId)
{
   for (int i = 0; i < 10; i++)
   {
      this.Response.Write(i.ToString());
      this.Response.Flush();
      Thread.Sleep(500); // Simulate time-consuming action
   }
   return "Done";
}

在视图中:

@Ajax.ActionLink("TestLink", "Create", new AjaxOptions() 
  { HttpMethod = "POST", UpdateTargetId="ProgressTarget" })<br />

<div id="ProgressTarget"></div>

任何人都可以帮助我做出渐进的行动结果吗? 谢谢!!

in my ASP.NET MVC3 Project, I've got an action which runs a certain amount of time.
It would be nice, if it could send partial responses back to the view.
The goal would be to show the user some progress-information.
Has anybody a clue how to make that work?

I did a try with some direct output to the response, but it's not being sent to the client in parts but all on one block:

[HttpPost]
public string DoTimeConsumingThings(int someId)
{
   for (int i = 0; i < 10; i++)
   {
      this.Response.Write(i.ToString());
      this.Response.Flush();
      Thread.Sleep(500); // Simulate time-consuming action
   }
   return "Done";
}

In the view:

@Ajax.ActionLink("TestLink", "Create", new AjaxOptions() 
  { HttpMethod = "POST", UpdateTargetId="ProgressTarget" })<br />

<div id="ProgressTarget"></div>

Can anybody help me making progressive action-results?
Thanks!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

表情可笑 2024-10-16 05:25:04

以下是实现此操作的方法:首先定义一些类,该类将保存长时间运行操作的状态 ->您将需要 id、进度、结果等属性,...然后您将需要两个控制器操作:一个将启动任务,另一个将返回进度。 Start 操作将生成一个新线程来执行长时间运行的操作并立即返回。任务启动后,您可以将此操作的状态存储到一些公共存储中,例如给定任务 ID 的应用程序。

第二个控制器操作将传递任务 ID,它将查询应用程序以获取给定任务的进度。在此期间,后台线程将执行,每次执行时,它将更新应用程序中任务的进度。

最后一部分是客户端:您可以使用 AJAX 定期轮询进度控制器操作并更新进度。

Here's how you could implement this: start by defining some class which will hold the state of the long running operation -> you will need properties such as the id, progress, result, ... Then you will need two controller actions: one which will start the task and another one which will return the progress. The Start action will spawn a new thread to execute the long running operation and return immediately. Once a task is started you could store the state of this operation into some common storage such as the Application given the task id.

The second controller action would be passed the task id and it will query the Application to fetch the progress of the given task. During that time the background thread will execute and every time it progresses it will update the progress of the task in the Application.

The last part is the client: you could poll the progress controller action at regular intervals using AJAX and update the progress.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文