Process running on computer after application exit - c#

I have a question, I created an application on visual studio using C# and Window Forms, but every time it runs, if the application close (either manually by the person or when it reach the end) it continue running on the process of the computer, so if I open and close the application 3 times there will be 3 processes with the same name activated. How can I prevent that from happening? So far the only way for me to close it is going to Window Task Manager and closing it manually, which is a pain...
Any ideas?

if you want to kill all processes and exit from application then first you need to kill threads in background
Application.ExitThread();
and then exit from application
Environment.Exit();

You can use Saif's answer which forces background threads to abort, but I'd recommend you manage your threads better. If you have threads that run for an extended period of time, you should have a flag (a boolean that can be accessed from anywhere in your code) that tells the threads they should stop running. This is a safer method than
Application.ExitThread();
because it allows you to flush and close streams, disconnect your socket connections or tidy up whatever you're doing in your threads.

Well, based on this problem you can check if your application is running on your application startup. That way you only start the process if it is not running:
I´m going to check for example notepad:
Process[] pname = Process.GetProcessesByName("notepad");
if (pname.Length == 0)
{
//The application is not running. Start your process here
}
else
{
//Your application is running. Do nothing
}

Related

Right way to run, kill and keep process running

In my application, which using another application (run in tray) to print receipts I need to do those three things:
Open process when on mainApplication startup
Close process when mainApplication closing or changing any information about printer
Keep process alive, if it get any error
First point is quiet easy, I just simply
Process.Start("_ReceiptPrinter.exe");
And process working ;)
But now, the two other issues:
Closing process. I've tried this code:
Process[] allProcs = Process.GetProcesses();
foreach (Process proc in allProcs)
{
ProcessThreadCollection myThreads = proc.Threads;
if (proc.ProcessName == "_ReceiptPrinter")
{
proc.Close();
}
}
Unfortunately, I can still see icon in tray, and process is still running.
Keep process alive. My main application is in WPF, that one from tray is written on WinForms. Maybe there is any way to handle ANY WinForm application exit event (well, any, but not this one, which just simply close it from another application), and reopen it?
proc.Close() asks it to close but there is no guarantee. Use:
proc.Kill();
The reason you still see a tray icon is that the icons are cached by an external process (windows explorer.)
The reason process.Close() does not close the application is because the application is not processing window messages (as this call simulates a WM_CLOSE request, per classic Windows API.)
The proper way to close the application is process.Close, not process.Kill(), further, as part of app/window close you need to unregister any tray icons you've registered with the system. This way any normal closure of your application will properly clean-up the tray.
Further, you can use a "critical finalizer" which would be guaranteed to run before application exit, except in total catastrophe scenarios.

C# - Terminate another proccess when mine still running

i was wrote some codes, when my apps still run, it will close another (example notepad) even the notepad is reopen it will close again, i've try some, but it will close when my apps startup , when my apps is running, and i open notepad, notepad wont close. here
foreach (Process Proc in Process.GetProcesses())
if (Proc.ProcessName.Equals("notepad"))
Proc.Kill();
Your code kills processes that are running at the time you code executes. Once your code has finished executing it no longer exerts any influence. It won't kill processes that are started after your code has finished executing.
Probably you need to detect when the target process starts, and then kill it. You can do that by polling which is rather inelegant. To avoid polling you need WMI. There are many examples of how to do this. For instance: How to detect a process start & end using c# in windows?

How to send a control-break (or equivalent signal) to console application process in .NET?

Suppose I start a Process for running a console application like 7z.exe (7-Zip Archiver). I am creating the Process without a window and I'm redirecting the standard output.
I want to know how to stop the Process other than "Process.Kill", because that causes an incomplete/corrupt archive file to be left behind.
If I press CTRL-BREAK when running 7z.exe from a normal command console window, it shuts down gracefully and deletes the incomplete file.
If cmd.exe can start a process and send it a ctrl-break signal, then how can my own application start a process and send it a ctrl-break (or equivalent) signal, so that the process shuts down gracefully?
You can do a thread.sleep to pause it if need be. If you want to stop it completely I'd set up a watch variable then pause your thread, handle any existing data (this is probably was 7zip is doing), and then do a process.kill. I don't think there is (or know of one) an way to automagically handle aborting a process "gracefully". It is up to you, the programmer, to handle an interrupted exit condition gracefully.

C# is there anyway to instruct a code block to finish processing before the app gets shut down?

I know this won't work in all scenarios, but please keep in mind the following 3 scenarios:
An IIS reset - if the code is running inside IIS
A Server restart or shut down
User closes the app (if its a Windows form or Console App).
Lets say I have a code block that runs a loop. Is there a way to ensure at least that the current loop item gets processed before the app shuts down.
Like this...
Loop runs: 100 items, app gets shutdown (for reasons above), app is busy with item in loop 53 for example. It first finishes all code for that item between the foreach... and then allows the app to gracefully shutdown.
Is this type of thing possible?
Nothing I would do but If it is ok to abuse the system you might be able to use the CriticalFinalizerObject
It is guaranteed to execute
even in situations where the CLR forcibly unloads an application domain or aborts a thread
I really don't think so. You are stuck in front of windows. Windows take that kind of decisions for you.. IF somebody is shutting down the pc, then you are just shut down. This is the same scenario as if they where a power failure. What will you do in that case?
For a normal application: While your code is running in a foreground thread (not ThreadPool or Thread.IsBackground == true) it will not be aborted mid-execution, unless the user forcibly quits the process.
If you are running your loop in a background thread, you can try handling the exit event of the application, waiting for the loop to finish or at least reach a stable state before being aborted.
In most apps you can handle close event and not allow it but you can't do anything when user decides to kill your process. So i would say that its not possible.
How about doing this. using a try catch and finally in the static void Main
Here even if you end task the application, finally will run. not sure about power failure.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new Form1());
}
finally
{
MessageBox.Show("I run always.");
}
}
Hope it helps

Alternative methods to kill a running process in C#

I am having a bit of trouble trying to terminate a process, I realize there is a fair amount of recourses on this site alone, but I was wondering if there's any alternative ways of terminating an application rather than something typical such as:
Process[] procs = Process.GetProcessesByName("test");
foreach (Process proc in procs)
proc.Kill();
There's Process.CloseMainWindow, which nicely asks the process to quit (as opposed to Process.Kill, which shoots down the process and can have negative side effects).
There are only 2 ways in C# to close the Process (AFAIK) using Process.Kill() and Process.CloseMainWindow(), Kill sends an immediate KILL signal to the application and forces it to close immediately. CloseMainWindow uses SendWindowMessage to send a CLOSE signal to the main application. Kill can be unsafe because it immediately stops the process. CloseMainWindow can be followed by Process.WaitForExit so that you can be sure that the application has closed and may continue to do work knowing that the process you told to exit has exited correctly. As posted by Heinzi's comment please be a little more specific I'm just trying to expand on what was said in the hopes that this is what you require.
Very simple, just need to get the process name and kill it, don't try to do anything fancy, sometimes less is more...
Process[] prs = Process.GetProcesses();
foreach (Process pr in prs)
{
if (pr.ProcessName == "test")
{
pr.Kill();
}
}
This idea is not good. There could be another running process(es) with that name. Do you want any process with that name to be terminated? Unless you are writing a Task Manager/Process Explorer kind of application, you should never do that. And even with TM kind of application, you close the process by grabbing its handle/Process object, and not by name.
Thy can't you ask the target process to close itself gracefully? May be you can use a named mutex, the target thread would wait on that mutex. When you signal that named-mutex from another process, the target thread would know it is time to exit and eventually exit.

Categories

Resources