perhaps I'm misinterpreting this part of Windows' Task Scheduler UI, but the following options suggest (to me) that a program is first asked nicely to stop, and then forcefully quit when that fails:
from the deepest corners of my mind, I remembered that Windows applications can respond to requests to quit; with that in mind, I was able to google up AppDomain.CurrentDomain.ProcessExit
. however, it appears that Task Scheduler's "stop the task..." and AppDomain.CurrentDomain.ProcessExit
do not work together as I had hoped; here is an example program I threw together that does not work:
using System;
using System.Threading;
using System.Windows.Forms;
namespace GimmeJustASec
{
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += new EventHandler(SuddenCleanup);
while(true)
{
Thread.Sleep(1000);
}
}
static void SuddenCleanup(object sender, EventArgs e)
{
MessageBox.Show("Hello!");
}
}
}
tl;dr my question is:
- can a program be written to respond to Task Scheduler stopping it? (or does Task Scheduler force-quit tasks in the rudest way possible?)
- if a program can be written in this way, how is the correct way to do so? (the way I tried is clearly not correct.)
- am I over-thinking all of this, and it would just be better to have the program time itself in a parallel thread? (perhaps with a max time set in app.config, or whatever.)
[edit] tried this variant, at Andrew Morton's request, with similar results:
using System;
using System.Threading;
using System.Windows.Forms;
using System.IO;
namespace GimmeJustASec
{
class Program
{
private static StreamWriter _log;
static void Main(string[] args)
{
_log = File.CreateText("GimmeJustASec.log");
_log.AutoFlush = true;
_log.WriteLine("Hello!");
AppDomain.CurrentDomain.ProcessExit += new EventHandler(SuddenCleanup);
while(true)
{
Thread.Sleep(1000);
}
}
static void SuddenCleanup(object sender, EventArgs e)
{
_log.WriteLine("Goodbye!");
}
}
}
after Task Scheduler stops the task, the .log file contains "Hello!" but not "Goodbye!"