我怎么知道进程是否正在运行?

res*_*efm 145 .net c# process

当我获得对a的引用时System.Diagnostics.Process,如何知道进程当前是否正在运行?

Pat*_*ins 237

这是一种使用名称的方法:

Process[] pname = Process.GetProcessesByName("notepad");
if (pname.Length == 0)
  MessageBox.Show("nothing");
else
  MessageBox.Show("run");
Run Code Online (Sandbox Code Playgroud)

您可以循环所有进程以获取ID以供以后操作:

Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist){
   Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}
Run Code Online (Sandbox Code Playgroud)

  • @MatthewD:C#`if/else`语句只有一行,不需要花括号来表示块语句.这也适用于`foreach`和`for`语句.它归结为编码风格. (4认同)
  • @MatthewD是的,实际上这适用于大多数语言(如Java).通常很好的做法是避免像这样的单行并总是使用花括号,因为将来你可能不得不在那里添加更多的语句,在这种情况下,当你需要时,大括号已经存在.但是对于这样的事情,如果你100%确定你只需要一个语句,那么可以做到并且语法上有效. (3认同)
  • 如果找不到该进程,请尝试删除扩展程序。(例如:.exe) (2认同)

res*_*efm 25

这是我在使用反射器后找到的最简单的方法.我为此创建了一个扩展方法:

public static class ProcessExtensions
{
    public static bool IsRunning(this Process process)
    {
        if (process == null) 
            throw new ArgumentNullException("process");

        try
        {
            Process.GetProcessById(process.Id);
        }
        catch (ArgumentException)
        {
            return false;
        }
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

Process.GetProcessById(processId)方法调用该ProcessManager.IsProcessRunning(processId)方法并抛出ArgumentException该进程不存在的情况.由于某种原因,ProcessManager班级是内部的......


Coi*_*oin 16

同步解决方案:

void DisplayProcessStatus(Process process)
{
    process.Refresh();  // Important


    if(process.HasExited)
    {
        Console.WriteLine("Exited.");
    }
    else
    {
        Console.WriteLine("Running.");
    } 
}
Run Code Online (Sandbox Code Playgroud)

异步解决方案:

void RegisterProcessExit(Process process)
{
    // NOTE there will be a race condition with the caller here
    //   how to fix it is left as an exercise
    process.Exited += process_Exited;
}

static void process_Exited(object sender, EventArgs e)
{
   Console.WriteLine("Process has exited.");
}
Run Code Online (Sandbox Code Playgroud)

  • 对于第一个选项:我怎么知道该过程是否首先启动? (5认同)
  • 请注意,如果出现问题(例如:无法检索退出代码),“HasExited”可能会引发异常。 (2认同)

Ael*_*eis 8

reshefm有一个非常好的答案; 但是,它没有考虑到从未开始过程的情况.

这是他发布的修改版本.

    public static bool IsRunning(this Process process)
    {
        try  {Process.GetProcessById(process.Id);}
        catch (InvalidOperationException) { return false; }
        catch (ArgumentException){return false;}
        return true;
    }
Run Code Online (Sandbox Code Playgroud)

我删除了他的ArgumentNullException,因为它实际上假设是一个空引用异常,它仍然被系统抛出,我还考虑了从未开始进程或使用close()方法关闭的情况.处理.


gun*_*sus 6

这应该是一个单行:

public static class ProcessHelpers {
    public static bool IsRunning (string name) => Process.GetProcessesByName(name).Length > 0;
}
Run Code Online (Sandbox Code Playgroud)