简体   繁体   中英

ASP.NET MVC Subprocess Return values

I wrote code like that

public void GitConnectAndFetch()
{   
    try
    {
        ProcessStartInfo startInfo = new ProcessStartInfo("git.exe");
        startInfo.UseShellExecute = false;                
        startInfo.WorkingDirectory = projectPath;                
        startInfo.RedirectStandardInput = true;
        startInfo.RedirectStandardOutput = true;
        startInfo.Arguments = "branch -a";
        Process process = new Process();
        process.StartInfo = startInfo;
        process.Start();
        string branchname = "";
        List<SelectListItem> ddgit = new List<SelectListItem>();
        while (process.StandardOutput.Peek() >= 0)
        {
            branchname = process.StandardOutput.ReadLine().Trim();
            if (branchname.Trim().StartsWith("remotes/origin/"))
            {                       
                ddgit.Add(new SelectListItem { Text = branchname.ToString().Replace("remotes/origin/",""), Value = branchname.ToString() });
            }
        }
        if (ddgit.Count == 0) ddgit.Add(new SelectListItem() { Text = "", Value = "" });
        process.WaitForExit();
        ViewBag.Branchlist = ddgit;
    }
    catch (Exception ex)
    {
        localLog(ex.Message);
        localLog(ex.StackTrace);
    }
}

[HttpGet]
public ActionResult Main()        
{
    GitConnectAndFetch();
    return View();
}

And I called it again after the post

[HttpPost]
public ActionResult Otomasyon(FormCollection form)
{
    GitConnectAndFetch();                    
    return View();
}

I think subprocess is working slowly and I'm calling it twice to fill the dropdown list on my mainpage, how can I make it run for once to close.

If you aren't expecting different values, then I would just cache the value of ddgit and if that cache exists, return it instead of executing the process.

First of all, method GitConnectAndFetch has side effects (setting data into ViewBag), this is not good. Transform it to pure function, that returns SomeBranchItem[].

Secondary, cache the result of GitConnectAndFetch. You may implement it via setting method's result into one private static field A and current timestamp into second static field B. Then on every request you should compare current timestamp and timestamp from field B to determine whether you can use cached data from A as result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM