When I get a reference to a System.Diagnostics.Process
, how can I know if a process is currently running?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
I tried Coincoin's solution :
Before processing some file, I copy it as a temporary file and open it.
When I'm done, I close the application if it is still open and delete the temporary file :
I just use a Process variable and check it afterwards :
Later I close the application :
It works ( so far )
It depends on how reliable you want this function to be. If you want to know if the particular process instance you have is still running and available with 100% accuracy then you are out of luck. The reason being that from the managed process object there are only 2 ways to identify the process.
The first is the Process Id. Unfortunately, process ids are not unique and can be recycled. Searching the process list for a matching Id will only tell you that there is a process with the same id running, but it's not necessarily your process.
The second item is the Process Handle. It has the same problem though as the Id and it's more awkward to work with.
If you're looking for medium level reliability then checking the current process list for a process of the same ID is sufficient.
Maybe (probably) I am reading the question wrongly, but are you looking for the HasExited property that will tell you that the process represented by your Process object has exited (either normally or not).
If the process you have a reference to has a UI you can use the Responding property to determine if the UI is currently responding to user input or not.
You can also set EnableRaisingEvents and handle the Exited event (which is sent asychronously) or call WaitForExit() if you want to block.
This is the simplest way I found after using reflector. I created an extension method for that:
The
Process.GetProcessById(processId)
method calls theProcessManager.IsProcessRunning(processId)
method and throwsArgumentException
in case the process does not exist. For some reason theProcessManager
class is internal...Synchronous solution :
Asynchronous solution:
Process.GetProcesses()
is the way to go. But you may need to use one or more different criteria to find your process, depending on how it is running (i.e. as a service or a normal app, whether or not it has a titlebar).