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)
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)
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()方法关闭的情况.处理.
这应该是一个单行:
public static class ProcessHelpers {
public static bool IsRunning (string name) => Process.GetProcessesByName(name).Length > 0;
}
Run Code Online (Sandbox Code Playgroud)