【问题标题】:c# console application respond every second command?c#控制台应用程序每秒响应一次命令?
【发布时间】:2018-06-27 22:11:39
【问题描述】:

我正在编写一个控制台应用程序“任务管理器”来学习更好的 C#。

我遇到了一个小问题。每次用户(我)输入不是命令的内容时,应用程序都应该查找具有我输入的名称/文本的进程。

到目前为止,它可以正常工作,但它只会在我输入文本时每秒钟响应一次。

这是我的代码:

    static void Main(string[] args)
    {
        string s = "Console Task Manager v1.0.0";
        Console.WriteLine();
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.SetCursorPosition((Console.WindowWidth - s.Length) / 2, Console.CursorTop);
        Console.WriteLine(s);
        Console.WriteLine("Type 'exit' for close this application.");
        Console.WriteLine("\nPlease type the process what are you looking for:");

        while (Console.ReadLine() != "exit")
        {
            GetProcesses();
        }
    }

    static void GetProcesses()
    {
        Process[] processes = Process.GetProcessesByName(Console.ReadLine());

        foreach(Process process in processes)
        {
            Console.WriteLine("ID: " + process.Id + " | Name: " + process.ProcessName);
            //process.Kill();
        }
    }

为了更好地想象我的问题,我为这个问题添加了一个屏幕截图。 谢谢你的帮助。

【问题讨论】:

    标签: c# command console-application


    【解决方案1】:

    您遇到此问题是因为您在两个地方有 Console.ReadLine()。第一个Console.ReadLine() 用于检查退出。第二个用于获取进程名称。然后第一个被再次调用,依此类推。

    static void Main(string[] args)
    {
        string s = "Console Task Manager v1.0.0";
        Console.WriteLine();
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.SetCursorPosition((Console.WindowWidth - s.Length) / 2, Console.CursorTop);
        Console.WriteLine(s);
        Console.WriteLine("Type 'exit' for close this application.");
        Console.WriteLine("\nPlease type the process what are you looking for:");
    
        while (Console.ReadLine() != "exit") // readline 1
        {
            GetProcesses();
        }
    }
    
    static void GetProcesses()
    {
        Process[] processes = Process.GetProcessesByName(Console.ReadLine()); // readline 2
    
        foreach(Process process in processes)
        {
            Console.WriteLine("ID: " + process.Id + " | Name: " + process.ProcessName);
            //process.Kill();
        }
    }
    

    如果你看一下程序流程,它是这样的:

    readline 1(仅用于检查退出)
    获取进程
    readline 2 - 获取进程名称
    GetProcesses 返回
    读取线 1
    获取进程
    readline 2 - 获取进程名称
    GetProcesses 返回
    ...

    修复它的一种方法是执行以下操作:

    static void Main(string[] args)
    {
        string s = "Console Task Manager v1.0.0";
        Console.WriteLine();
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.SetCursorPosition((Console.WindowWidth - s.Length) / 2, Console.CursorTop);
        Console.WriteLine(s);
        Console.WriteLine("Type 'exit' for close this application.");
        Console.WriteLine("\nPlease type the process what are you looking for:");
    
        string lastCommand = string.Empty;
        do
        {
            lastCommand = Console.ReadLine();
            if (lastCommand != "exit")
            {
                KillProcess(lastCommand);
            }
        } while (lastCommand != "exit");
    }
    
    static void KillProcess(string processName)
    {
        Process[] processes = Process.GetProcessesByName(processName);
    
        foreach(Process process in processes)
        {
            Console.WriteLine("ID: " + process.Id + " | Name: " + process.ProcessName);
            //process.Kill();
        }
    }
    

    编辑: 如果你想进一步扩展它并添加额外的命令,你可以做这样的事情,你有一个解析命令的新函数。

    /// <summary>
    /// Field that indicates whether or not the program should keep running.
    /// </summary>
    static bool keepRunning = true;
    
    static void Main(string[] args)
    {
      string s = "Console Task Manager v1.0.0";
      Console.WriteLine();
      Console.ForegroundColor = ConsoleColor.Cyan;
      Console.SetCursorPosition((Console.WindowWidth - s.Length) / 2, Console.CursorTop);
      Console.WriteLine(s);
      Console.WriteLine("Type 'exit' for close this application.");
      Console.WriteLine("\nPlease type the process what are you looking for:");
    
      do
      {
        string lastCommand = Console.ReadLine();
        ProcessCommand(lastCommand);
      } while (keepRunning);
    }
    
    /// <summary>
    /// Processes a command we've received.
    /// </summary>
    /// <param name="command">The command that was entered.</param>
    static void ProcessCommand(string command)
    {
      if (string.IsNullOrEmpty(command))
      {
        return;
      }
    
      // A command might have one or more parameters, these will be separated
      // by spaces (i.e. "kill 12345").
      string[] commandParts = command.Split(' ');
    
      // Process each command we know about.
      if (commandParts[0] == "exit")
      {
        keepRunning = false;
      }
      else if (commandParts[0] == "kill")
      {
        // This command needs 1 parameter.
        if (commandParts.Length < 2)
        {
          Console.WriteLine("kill command requires process name or ID");
          return;
        }
    
        // Try checking if the second value can be parsed to an integer. If so
        // we'll assume it's the process ID to kill. Otherwise, we'll try to 
        // kill the process by that name.
        int id;
        if (int.TryParse(commandParts[1], out id))
        {
          KillProcessByID(id);
        }
        else
        {
          KillProcessByName(commandParts[1]);
        }
      }
      // More commands can be added here.
    
      // This isn't a known command.
      else
      {
        Console.WriteLine("Unknown command \"" + command + "\"");
      }
    }
    
    static void KillProcessByName(string processName)
    {
      Process[] processes = Process.GetProcessesByName(processName);
    
      foreach (Process process in processes)
      {
        Console.WriteLine("ID: " + process.Id + " | Name: " + process.ProcessName);
        //process.Kill();
      }
    }
    
    static void KillProcessByID(int processID)
    {
      Process process = Process.GetProcessById(processID);
      if (process != null)
      {
        Console.WriteLine("ID: " + process.Id + " | Name: " + process.ProcessName);
        //process.Kill();
      }
    }
    

    【讨论】:

    • 谢谢你。但是在这个例子中,我怎样才能添加一个新的命令,比如“kill + processId”来杀死一个进程?
    • @MendaxM。 if (process.ProcessName.Equals(processName, StringComparison.OrdinalIgnoreCase)) { process.Kill(); }
    • @RufusL 谢谢,但我想添加一个新命令来终止进程。
    • 你现在已经保存了lastCommand,所以你可以检查它的价值并做一些具体的事情。但这是一个不同的问题。如果这个答案解决了这个问题,您应该将其标记为“已回答”,然后尝试实施更强大的菜单,如果遇到困难,请返回一个新问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 2012-08-14
    • 2011-08-06
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多