The program’s code is like below:
using System.Diagnostics;
class Test
{
static void Main()
{
using (Process p = Process.Start("notepad.exe"))
{
}
}
}
The problem is when this program has been closed and the Notepad is still running, the Notepad will lock it. And I don’t want to close the Notepad.
I tried to use Unlocker to detect the problem.
The result screen shot is like below:
So what I want is starting a exe file and dispose all thread resources immediately. Or I can’t uninstall my program until all the program opened by it are closed. That may cause unpleasant user experience. Requiring system restart is also unpleasant. Unlocker can do it nicely. If I use Unlocker to unlock the parent folder, it won’t close the Notepad, and then I can delete this program file normally.
The problem is that you never close the running process, so it continues to run, which causes Unlocker to indicate that it is locked.
I know you think you did, because you called
p.Close(), but the trick is that theProcess.Close()method does not cause the process to close. It does not send aWM_CLOSEorWM_QUITmessage to the Notepad window. All it does is free the resources associated with the process.Instead, you need to use the
Process.CloseMainWindow()method. This will send the window aWM_CLOSEmessage, causing it to close properly.So update your code to look like this (as someone else mentioned, there’s no need to explicitly call
Disposeif you’ve already wrapped the object creation in ausingstatement):Note that you could use the
Process.Kill()method, but this is like turning off your computer by ripping the power cord out of the wall. Instead of asking the application to close nicely, it forces it to terminate, just like clicking “End Task” in Task Manager. It should therefore be used only when the process is locked up or otherwise not responding to polite requests to close.Also, as Rolice mentioned in a comment, the above code isn’t going to be very useful. You’re just starting Notepad and then immediately closing it.
Instead, you probably want to start the process, allow the user to interact with it, and then clean up after they’re done with it.
In that case, you need to use the
Process.WaitForExit()method. This method will block the calling thread, waiting indefinitely for the process to exit. When the user finally closes Notepad, control will return to your application’s thread and you can callp.Close().For example: