从 ASP.NET MVC 调用控制台应用程序,但不想等待响应

发布于 2024-11-17 10:55:28 字数 4540 浏览 2 评论 0原文

我正在尝试实现这样的目标。

    private Process p;

    //
    // GET: /Home/
    [HttpGet]
    public ActionResult Index()
    {
        return View(new Contents() { Text = "Hello" });
    }

    [HttpPost]
    public ActionResult Processing()
    {
        // Get the file path of your Application (exe)
        string filePath = @"Z:\Junk\MVCtoConsole\Sample Console App\bin\Debug\Sample Console App.exe";

        ProcessStartInfo info = new ProcessStartInfo(filePath);
        info.RedirectStandardOutput = true;
        info.UseShellExecute = false;

        p = Process.Start(info);
        p.WaitForExit(1);

        Session["pid"] = p.Id;

        return View("Index", new Contents() { Text = "Processing" });
    }

    [HttpPost]
    public ActionResult Kill()
    {
        int pid = (int)Session["pid"];

        p = Process.GetProcessById(pid);

        p.Kill();

        return View("Index", new Contents() { Text = "Killed" });
    }

    public ActionResult Update()
    {
        int pid = (int)Session["pid"];

        p = Process.GetProcessById(pid);

        return View("Index", new Contents() { Text = p.StandardOutput.ReadToEnd() });
    }

但是在调用更新视图时出现以下错误...

“/”应用程序中的服务器错误。

StandardOut 尚未重定向或 该过程尚未开始。

描述:未处理的异常 执行期间发生的 当前的网络请求。请查看 堆栈跟踪以获取有关的更多信息 错误及其起源 代码。

异常详细信息: 系统.InvalidOperationException: StandardOut 尚未重定向或 该过程尚未开始。

来源错误:

第 56 行:p = Process.GetProcessById(pid);第 57 行: 第58行:返回 查看(“索引”,新内容(){文本= p.StandardOutput.ReadToEnd() });线 59: } 第 60 行: }

源文件: Z:\Junk\MVCtoConsole\MVCtoConsole\Controllers\HomeController.cs 行数:58

堆栈跟踪:

[无效操作异常: StandardOut 尚未重定向或 该过程尚未开始。]
System.Diagnostics.Process.get_StandardOutput() +1172937 MVCtoConsole.Controllers.HomeController.Update() 在 Z:\垃圾\MVCtoConsole\MVCtoConsole\Controllers\HomeController.cs:58 lambda_method(执行范围, ControllerBase , 对象[] ) +40
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase 控制器,对象[]参数)+17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext 控制器上下文,IDictionary<代码>2 参数)+178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext 控制器上下文、动作描述符 动作描述符,IDictionary2 参数)+24
System.Web.Mvc.<>c_DisplayClassd.b_a() +52 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter 过滤器、ActionExecutingContext preContext,Func1 延续)+254 System.Web.Mvc.<>c__DisplayClassf.b__c() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext,IList1个过滤器, 动作描述符动作描述符, IDictionary2 个参数)+192
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext 控制器上下文,字符串操作名称) +314 System.Web.Mvc.Controller.ExecuteCore() +105 System.Web.Mvc.ControllerBase.Execute(RequestContext 请求上下文)+39
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext 请求上下文)+7
System.Web.Mvc.<>c__DisplayClass8.b__4() +34 System.Web.Mvc.Async.<>c__DisplayClass1.b__0() +21 System.Web.Mvc.Async。<>c__DisplayClass8
1.b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +59 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult 异步结果)+44
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult 结果)+7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8690318 System.Web.HttpApplication.ExecuteStep(IExecutionStep 步骤,布尔值&同步完成) +155

版本信息:Microsoft .NET 框架版本:2.0.50727.5446; ASP.NET版本:2.0.50727.5420

关于如何实现这一点有什么想法吗?

哦,我的控制台应用程序现在没有做太多事情,因为我只是想知道是否可以这会起作用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Sample_Console_App
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Triggered");

            for (int i = 0; i < 100000; i = i + 100)
            {
                Console.WriteLine(i);
                Thread.Sleep(1000);
            }
        }
    }
}

I am trying to achieve something like this.

    private Process p;

    //
    // GET: /Home/
    [HttpGet]
    public ActionResult Index()
    {
        return View(new Contents() { Text = "Hello" });
    }

    [HttpPost]
    public ActionResult Processing()
    {
        // Get the file path of your Application (exe)
        string filePath = @"Z:\Junk\MVCtoConsole\Sample Console App\bin\Debug\Sample Console App.exe";

        ProcessStartInfo info = new ProcessStartInfo(filePath);
        info.RedirectStandardOutput = true;
        info.UseShellExecute = false;

        p = Process.Start(info);
        p.WaitForExit(1);

        Session["pid"] = p.Id;

        return View("Index", new Contents() { Text = "Processing" });
    }

    [HttpPost]
    public ActionResult Kill()
    {
        int pid = (int)Session["pid"];

        p = Process.GetProcessById(pid);

        p.Kill();

        return View("Index", new Contents() { Text = "Killed" });
    }

    public ActionResult Update()
    {
        int pid = (int)Session["pid"];

        p = Process.GetProcessById(pid);

        return View("Index", new Contents() { Text = p.StandardOutput.ReadToEnd() });
    }

But I get the following errors when calling the update view...

Server Error in '/' Application.

StandardOut has not been redirected or
the process hasn't started yet.

Description: An unhandled exception
occurred during the execution of the
current web request. Please review the
stack trace for more information about
the error and where it originated in
the code.

Exception Details:
System.InvalidOperationException:
StandardOut has not been redirected or
the process hasn't started yet.

Source Error:

Line 56: p =
Process.GetProcessById(pid); Line 57:
Line 58: return
View("Index", new Contents() { Text =
p.StandardOutput.ReadToEnd() }); Line
59: } Line 60: }

Source File:
Z:\Junk\MVCtoConsole\MVCtoConsole\Controllers\HomeController.cs
Line: 58

Stack Trace:

[InvalidOperationException:
StandardOut has not been redirected or
the process hasn't started yet.]
System.Diagnostics.Process.get_StandardOutput()
+1172937 MVCtoConsole.Controllers.HomeController.Update()
in
Z:\Junk\MVCtoConsole\MVCtoConsole\Controllers\HomeController.cs:58
lambda_method(ExecutionScope ,
ControllerBase , Object[] ) +40
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase
controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary2
parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor
actionDescriptor, IDictionary
2
parameters) +24
System.Web.Mvc.<>c_DisplayClassd.b_a()
+52 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter
filter, ActionExecutingContext
preContext, Func1 continuation) +254
System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c()
+19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext
controllerContext, IList
1 filters,
ActionDescriptor actionDescriptor,
IDictionary2 parameters) +192
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
+314 System.Web.Mvc.Controller.ExecuteCore()
+105 System.Web.Mvc.ControllerBase.Execute(RequestContext
requestContext) +39
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext
requestContext) +7
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4()
+34 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
+21 System.Web.Mvc.Async.<>c__DisplayClass8
1.b__7(IAsyncResult
_) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End()
+59 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult
asyncResult) +44
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+8690318 System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
+155

Version Information: Microsoft .NET
Framework Version:2.0.50727.5446;
ASP.NET Version:2.0.50727.5420

Any Ideas as to how this can be achieved?

Oh my console app isn't doing very much just now, as I am just trying to find out if this will work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Sample_Console_App
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Triggered");

            for (int i = 0; i < 100000; i = i + 100)
            {
                Console.WriteLine(i);
                Thread.Sleep(1000);
            }
        }
    }
}

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

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

发布评论

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

评论(1

南汐寒笙箫 2024-11-24 10:55:28

您还需要设置

p.UseShellExecute = False

抱歉没有看到您已经设置了它,

您应该在询问输出之前检查 p 状态,那时可能已经结束

You need to set also

p.UseShellExecute = False

Sorry didn't saw that you already set it

you should check p state before asking for output could be already ended by that time

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