Home > Backend Development > C++ > How Can I Check if a C# Process Instance Is Still Running?

How Can I Check if a C# Process Instance Is Still Running?

Barbara Streisand
Release: 2025-01-15 21:38:48
Original
904 people have browsed it

How Can I Check if a C# Process Instance Is Still Running?

How to determine the status of a running process in C#

In .NET, the System.Diagnostics.Process class provides access to running process information. A critical task that may arise is determining whether a specific process is still active.

Question: How to determine if a Process instance is currently running?

Answer:

Method 1: Use process name

Process[] pname = Process.GetProcessesByName("notepad");
if (pname.Length == 0)
  MessageBox.Show("进程未运行");
else
  MessageBox.Show("进程正在运行");
Copy after login

In this code, we retrieve a collection of all processes that match a specified name (e.g., "notepad"). If the length of this collection is zero, it means that no process by that name is running.

Method 2: Traverse all processes

Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist){
   Console.WriteLine($"进程名称:{theprocess.ProcessName},进程ID:{theprocess.Id}");
}
Copy after login

This method involves looping through all running processes and checking the name and identification number of each process. This is a more general approach that finds all processes, not just those with a specified name.

The above is the detailed content of How Can I Check if a C# Process Instance Is Still Running?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template