Call a Console App from ASP.NET MVC, but don't want to wait for the response

这一生的挚爱 提交于 2019-12-12 02:14:30

问题


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, IList1 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);
            }
        }
    }
}

回答1:


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



来源:https://stackoverflow.com/questions/6490666/call-a-console-app-from-asp-net-mvc-but-dont-want-to-wait-for-the-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!