ASP.NET MVC子进程返回值

问题描述 投票:0回答:2

我写了这样的代码

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();
}

我在帖子发布后再次致电

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

我认为子进程运行缓慢,我两次调用它来填充主页上的下拉列表,如何使其运行一次才能关闭。

c# asp.net-mvc subprocess
2个回答
0
投票

如果您不期望使用其他值,那么我将仅缓存ddgit的值,如果该缓存存在,则将其返回,而不是执行该过程。


0
投票

首先,方法GitConnectAndFetch具有副作用(将数据设置到ViewBag中),这不好。将其转换为纯函数,该函数返回SomeBranchItem []。

其次,缓存GitConnectAndFetch的结果。您可以通过将方法的结果设置到一个私有静态字段A中并将当前时间戳设置到第二个静态字段B中来实现它。然后,在每个请求上,您都应该比较当前时间戳和字段B中的时间戳,以确定是否可以使用A中的缓存数据作为结果。

© www.soinside.com 2019 - 2024. All rights reserved.