Danrex
Danrex

Reputation: 1655

Can't close down a process in C#

I am running an executable that opens a windows form from a webform. In visual studio the winform program runs a method and then closes the windows form correctly and shuts down the program. But when I run the same file as an executable it keeps the windows form open. I can see that this executable process is still running as SmartSheetAPI.exe.

enter image description here

When I check in properties the name of the file is "SmartSheetAPI.exe". If I end this process in the task manager it shuts down the windows form so I know that is the issue. However, I have tried using the below code on the webform to kill the process but again it doesn't work.

Process process = new Process();
process.StartInfo.FileName = @"P:\Visual Studio 2013\Projects\Smartsheet\SmartsheetAPI\obj\Debug\SmartSheetAPI.exe";
process.Start();
foreach (var processes in Process.GetProcessesByName("SmartSheetAPI.exe"))
{
    process.Kill();
}

Does anyone know how to shut this thing down. As I say it works well in the SmartSheetAPI program in visual studio but doesn't shutdown the window as an executable. I just need to shut down this process once it has run the method.

EDIT: The process that isn't closing is the vshost.exe and as such it is keep my application from closing for some reason (i.e. the windows form remains open). If I process.kill() this everything shuts down as required. However, the problem is that when I run the executable of that file the windows form stays open but I can't find the vshost.exe running to close it? I have disabled it and now the process that won't close is the SmartSheetAPI.exe file which is the program I am currently running. I just want to exit out of this program, but nothing I try seems to work.

Upvotes: 0

Views: 4805

Answers (1)

Quality Catalyst
Quality Catalyst

Reputation: 6795

After calling the Kill method, call the WaitForExit method to wait for the process to exit, or check the HasExited property to determine if the process has exited.

Process process = new Process();
process.StartInfo.FileName = @"P:\Visual Studio 2013\Projects\Smartsheet\SmartsheetAPI\obj\Debug\SmartSheetAPI.exe";
process.Start();
// do some stuff while process is alive ...
process.Kill();
process.WaitForExit();
// do stuff after the process has been killed ...

For more details see here: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill(v=vs.110).aspx

If your process cannot be killed it is probably waiting for something else. You might want to investigate that rather than forcing your application to be terminated.

Upvotes: 3

Related Questions