How to delete a running application in C#? - c#

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);

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

C# Process.Start - how to enforce WaitForExit

I have a console app that calls other console apps.
I am using the following link for howto: https://robindotnet.wordpress.com/2010/03/21/how-to-pass-arguments-to-an-offline-clickonce-application/
I cannot instantiate Process and use that as I get the error message "The specified executable is not a valid application for this OS platform."
I can call the apps using static version of Process e.g.
Process.Start(shortcutPath, arguments);
or
Process.Start(shortcutPath, arguments).WaitForExit();
However, I cannot get the Process to WaitForExit - one app is called and after a while, before the first app completes, the second one is called - which is a problem as it depends on the first app to complete.
Any suggestions on how to get Static version of Process to wait for exit (alt. how to instantiate Process and be able to call clickonce deployed apps?)
Process.Start Method (String, String) has a return value of System.Diagnostics.Process
Which is according to https://msdn.microsoft.com/en-us/library/h6ak8zt5%28v=vs.110%29.aspx is:
A new Process that is associated with the process resource, or null if no process resource is started. Note that a new process that’s started alongside already running instances of the same process will be independent from the others. In addition, Start may return a non-null Process with its HasExited property already set to true. In this case, the started process may have activated an existing instance of itself and then exited.
So I would check whether process.HasExited is true before calling WaitForExit
var process = Process.Start(shortcutPath, arguments);
if (process != null && process.HasExited != true)
{
process.WaitForExit();
}
else
{
// Process is null or have exited
}
Ok, after bashing my head against a wall for the best part of a day, I found this... Start an offline ClickOnce Application and wait for Exit
Used the mutex option. Fek me Microsoft, you've take something that used to be really simple and made a real horse's ass out of it.
I was just about to scrap my called exe's and create one monster - was feeling ill at the thought.

Process.Kill() and process events

Here is the situation:
I have to create a program that would input another processes output stream into textbox. That it self wouldn't cause too much problem. What does, however, is the fact that I have to run 5 instances of this console application and redirect output to 5 textboxes, as well as to be able to kill any of these processes at any time. As far as I have learned, the best way to do this is asynchronously. But the problem here is with killing processes, that are created on different thread. How do I kill it without having access to it since it doesn't exist in scope where I have to kill it. My best guess is to get its PID on Process.Start(), so I can kill it, so...
Is it possible to fire any event from process on Process.kill() command?
And if not - is there a way to kill a process in about the same time interval as Process.Kill() that does fire some sort of event?
Or maybe someone could suggest me some other approaches or best practice on how these problems are usually solved?
EDIT: The reason I am running all processes on different threads is that I use Thread.Sleep() on some of them if there is and input parameter that tell me that the process must be killed after x seconds.
Process.Kill() command for some reason, does, in fact, fire process exited event. Easiest way for me to know that the process was killed, was by making a volatile string that holds information about how it ended. (Change it to "killed" before process.kill etc...)
First of all you do not need Threads at all. Starting a process is async in itself, so Process.Start(...) does not block and you can create as many processes as you want.
Instead of using the static Process.Start method you should consider creating Process class instances and set the CanRaiseEvents property to true. Further there are a couple of events you can register (per instance) - those will only raise if CanRaiseEvents is set to true, but also after a process is/has exited (including Kill() calls).
When you call
Process.Start()
it returns a Process class instance, which you can use to retrieve information from it output and kill that process any time
Process p = Process.Start("process.exe");
//some operations with process, may be in another thread
p.Kill()

ASP.NET|Process Class- Runing And Stoping Process

few days ago, my freind asked me to build him a proagram that start and stop process.
so, as easy as it is. i did the next code:
(using System.Diagnostics)
Process process;
process = Process.start("SOMEONE.exe");
Process.Kill();
Now, thats it the easy part. everything works. but. when i do the same code in asp.net, its strat the process, but when you kill the process, nothing happnd. no matter what i did, any one have any solion to the next problem :(?
From MSDN:
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.
AppPool in IIS needs to run under LOCAL Account - otherwise ASP.NET doesn't have enough rights to start/stop processes on the server.

How to kill a process launched from a thread (created by threadpool) in C#?

I have written a windows service, which monitors a database table for pending jobs and spawns threads to run those jobs and each of these threads in turn launches a process to do the actual work (the process is a Microsoft utility, not a custom one). This works fine, but if one of the jobs is taking longer than usual, I would like to kill that job.
How can this be done? Do I need to abort the thread OR kill the process launched by the thread? I also need to save the standard output of that process in a text file. I use the following code to do that.
using (Process process = Process.Start(startInfo))
{
LogToTextFile(process.StandardOutput.ReadToEnd());
process.WaitForExit();
exitCode = process.ExitCode;
}
Is it possible for the thread to check a flag in the same table and kill the running process, so that it doesn't need to be aborted? I use ThreadPool.QueueUserWorkItem to create a thread. What is the most reliable to way to stop these running processes without stopping the windows service?
Process.Kill is what you're looking for. Killing the thread would be unwise and would have no effect upon the process that it launched.
Assuming you want to wait 60 seconds for the process to finish, you could use this:
using (Process process = Process.Start(startInfo))
{
LogToTextFile(process.StandardOutput.ReadToEnd());
if(process.WaitForExit(60000))
{
exitCode = process.ExitCode;
}
else
{
process.Kill();
}
}
To be doubly clear, do not kill a ThreadPool thread.

Wait till process is no longer running OR until timeout has passed, whichever happens first

I want to kill a process running on the machine using taskkill if they're still running after X seconds (a windows service was stopped but it takes time for processes to dissapear)
What's the most correct way to accomplish the above in C# (.net 2.0 or possibly 3.0)?
I've utility method for verifying whether a process is still running, given the process name (using Process.GetProcesses()).
(As the process is not spawned by my code, I can't use WaitTillExit to know when it's no longer running)
PS: the process runs on a remote machine
In fact, you can use Process.WaitForExit().
Simply get the process to wait for via
Process p = Process.GetProcessById(iYourID);
And then call
if(!p.WaitForExit(iYourInterval))
{
p.Kill();
}
You can also get processes via their name by
Process.GetProcessesByName(strYourProcessName);
You could call Process.WaitForExit, passing the appropriate timeout. This way you won't need to use your own check to see whether the process is still running.
Process p = ...
bool exited = p.WaitForExit(10000); // 10 seconds timeout

Categories