How to delete a running application in C#?

Viewed 167

I need to delete a running application from Windows. I killed all the processes with process name. While deleting immediately I got some error message. But after delaying task for 3 seconds, the application got deleted without any problems.

Can anyone explain why this is happening?

foreach (var process in Process.GetProcessesByName(appName))
{
    process.Kill();
}

System.Threading.Tasks.Task.Delay(1000 * 3).Wait(); // if we try to delete directly after killing process then error occurs
System.IO.Directory.Delete(sourceFolder, true);
1 Answers

It is happening because this is how it was designed to behave:

From Process.Kill documentation:

Note

The Kill method executes asynchronously. 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.

Related