【发布时间】:2012-01-18 16:41:51
【问题描述】:
我想做的是:
1) 从 MVC 视图中,启动一个长时间运行的进程。就我而言,这个过程是一个单独的控制台应用程序正在执行。控制台应用程序可能会运行 30 分钟,并定期控制台。写入其当前操作。
2) 返回 MVC 视图,定期轮询服务器以检索我已重定向到 Stream(或任何我可以访问它的地方)的最新标准输出。我会将新检索的标准输出附加到日志文本框或类似的东西。
听起来相对容易。虽然我的客户端编程有点生疏,但我在实际流式传输时遇到了问题。我认为这不是一个不寻常的任务。有人在 ASP.NET MVC 中找到了一个不错的解决方案吗?
最大的问题似乎是在执行结束之前我无法获得 StandardOutput,但我能够通过事件处理程序获得它。当然,使用事件处理程序似乎失去了我的输出焦点。
这就是我目前为止的工作......
public ActionResult ProcessImport()
{
// Get the file path of your Application (exe)
var importApplicationFilePath = ConfigurationManager.AppSettings["ImportApplicationFilePath"];
var info = new ProcessStartInfo
{
FileName = importApplicationFilePath,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false
};
_process = Process.Start(info);
_process.BeginOutputReadLine();
_process.OutputDataReceived += new DataReceivedEventHandler(_process_OutputDataReceived);
_process.WaitForExit(1);
Session["pid"] = _process.Id;
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
void _process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
_importStandardOutputBuilder.Insert(0, e.Data);
}
public ActionResult Update()
{
//var pid = (int)Session["pid"];
//_process = Process.GetProcessById(pid);
var newOutput = _importStandardOutputBuilder.ToString();
_importStandardOutputBuilder.Clear();
//return View("Index", new { Text = _process.StandardOutput.ReadToEnd() });
return Json(new { output = newOutput }, "text/html");
}
我还没有编写客户端代码,因为我只是点击 URL 来测试操作,但我也很感兴趣您将如何处理此文本的轮询。如果您也可以为此提供实际代码,那就太好了。我假设您在启动将使用 ajax 调用返回 JSON 结果的服务器的进程后运行一个 js 循环......但同样,它不是我的强项,所以很想看看它是如何完成的。
谢谢!
【问题讨论】:
标签: asp.net-mvc ajax json stream redirectstandardoutput