I have a .Net Windows Application that runs continually processing data. I get occasional problems because the user has inadvertently got 2 instances running. I have added code to prevent a second instance from running. I usually stop it myself ysing Task Manager > End Process. Is there a better way of terminating the program than this? Preferably something I can put in the Task Scheduler to run nightly.
There are a pair of little known command line programs that do what Task Manager does,
taskkill. Use the
/im switch to specify a process name.
You've identified several things related to process management that you'd like your application to be capable of doing. You've also mentioned that you want this to be highly automated (you are wanting to automatically kill it on a regular interval). To do that you're going to use a 'Scheduled Task'.
I suggest that you actually utilize the 'Task Scheduler' better to begin with. You can set it up to run exactly how you like. Then instead of invoking your application you can just invoke the 'Scheduled Task'. This will give you many advantages. Not the least of which being a fully implemented GUI easy enough for any system administrator to configure to their exact needs (and they are already used to it, most likely).
Even the single instance part of your application could have been done with 'Scheduled Tasks' alone (but using both ways may be better; to be sure no can simply make a copy of the task and run that to bypass the rule).
Using the circled drop down you may select how your application recycles its processes. Not pictured is an option to
Stop the new Instance which is what you are doing now with your code. The difference is that this setting is specific to the task; not the entire application (which may not be good enough).
If you have selected the 'Allow task to be run on demand' checkbox then you may run your task from the command line like this:
schtasks /Run /TN "task name"
If you want to end it, use:
schtasks /End /TN "task name"
Once setup, a scheduled task can be exported to other systems easily as well.
Right click on the task and select
Export... when you have it working. This file can later be added to any system by using the Import... command:
schtasks /Create [/S <system> [/U <username> [/P [<password>]]]] /XML <xmlfile> /TN <taskname>
We've only looked at a few of the available options you have here. You never know how people will need to use your application in the future and this allows you to have a lot of functionality for free. You may want to schedule this or you may prefer to just run it manually. That is up to you (and ultimately the end user as well; which is a good thing usually).