I'd like to create a new process which will clean up after itself, even if the calling process has terminated. I've mocked up an example be开发者_StackOverflowlow, using notepad to display a temporary file, which I'd like to be deleted after notepad is closed.
In the code below, this works as expected if I uncomment the WaitForExit() line or alternatively go into a infinite loop to mimic the calling program running. The main problem is when the calling program finishes, since the event is no longer handled.
I'd appreciate any suggestions on how to handle this case.
Regards,
Chris
static void Main(string[] args)
{
string filename = @"c:\temp\example.txt";
if (!File.Exists(filename))
File.WriteAllText(filename, "abc");
ProcessStartInfo psi = new ProcessStartInfo("notepad", filename);
Process cmdProcess = new Process();
Process p = new Process();
psi.CreateNoWindow = true;
p.EnableRaisingEvents = true;
p.StartInfo = psi;
p.Exited += (sender, e) => { File.Delete(filename); };
p.Start();
//p.WaitForExit();
}
A sneaky way would to write a batch file which does approx this:
notepad c:\temp\example.txt
del c:\temp\example.txt
and then have your process execute the batch instead.
Working sample (save as c:\test.bat):
echo FOO > c:\test.txt
notepad c:\test.txt
del c:\test.txt
del c:\test.bat
If the calling process has exited it can no longer do anything; it doesn't exist.
One option would be to create another thread that is not a background thread (set IsBackground
to false) and call WaitForExit on that thread; that will keep the process alive during normal exit from Main. However, this cannot do anything if the process terminates abnormally (task manager kill, or simply pulling out the power).
精彩评论