If a routine is running periodically by way of a System.Threading.Timer
, what can be done to prevent this routine from being aborted mid-way due to the termination of the host application?

- 22,579
- 65
- 193
- 321
-
1The timer is owned by the application; if the application terminates, so goes the timer. If your app is shut down gracefully, you could signal to the timer routine to clean up, but if someone force-aborts the app, there's not much you can do. – Joe Nov 17 '12 at 22:40
-
@Joe: would be there some way to allow the timer thread to carry on with its current iteration and then terminate? – CJ7 Nov 17 '12 at 22:46
-
@CJ7: if a part of application is not finished, the application is not finished too, by definition. – Vlad Nov 17 '12 at 22:47
-
@Vlad: whether the application is technically 'finished' is not my concern. What I need is to prevent the timer routine from being interrupted because it may not complete necessary database updates etc. I don't mind if this runs on after the host app appears to have terminated. – CJ7 Nov 17 '12 at 22:50
-
What if someone pulls the plug? You should be prepared for the possibility that things terminate before everything you expect to finish, finish. In the normal termination case, you should be able to signal your timer thread to wrap things up immediately. – Joe Nov 17 '12 at 23:24
-
See http://stackoverflow.com/a/9062414/327528 – CJ7 Nov 20 '12 at 13:28
3 Answers
Well, you cannot possibly do anything if the application is terminating; however you can prevent the implicit application termination by exit from main
(closing the main window, etc.) if you open a non-background thread.
You can make the timer to run at that thread, however you cannot do it with System.Threading.Timer
, as it runs on thread pool threads (which are background ones). You can e. g. start a dispatcher on that thread and run a DispatcherTimer
(if you are using WPF).

- 35,022
- 6
- 77
- 199
There is no way to guarantee that your thread won't be terminated abnormally. Any number of things can go wrong: an unexpected power failure, user terminating the application with Task Manager, or a bug in your program that crashes the thread are just three possibilities.
If you're doing a multi-stage database update that, if interrupted, would leave your database in a corrupted or inconsistent state, then you should be using transactions.

- 131,090
- 20
- 188
- 351
This code should cause the main thread to block for 10 seconds waiting for any queued timer callbacks to finish. This can be run at the exit point of the host application.
Dim waitHnd As WaitHandle = New AutoResetEvent(False)
Timer1.Dispose(waitHnd)
waitHnd.WaitOne(10000)

- 22,579
- 65
- 193
- 321