I am using System.Threading.Timer in my Windows service and locking the callback method using Monitor.TryEnter, so it’s non-reentrant. Inside the callback, I am looping over some database objects (Linq to SQL entities) and performing some IO tasks. On each iteration of the loop, I am changing some properties of entity to flag it as processed. After the loop exits, I call SubmitChanges on the datacontext, which persists the changes to the database. The following problem arises: if the service is stopped while the callback is executing, some of the IO tasks may have already been performed, but the records have not been flagged as processed in the database (i.e. SubmitChanges has not been called yet) — clearly, not what I want to happen. Somehow, I need to communicate to the callback worker thread that the OnStop event has fired to allow it to submit changes and wrap things up. How best to do this?
I am using System.Threading.Timer in my Windows service and locking the callback method using
Share
1st decide if you will finish the tasks that callback performs or you will rollback them. So if you decide to finish the tasks, you will perform the callback to the end. Time should be canceled in OnStop already. If you will go with the second option (rollback) your code will look something like that:
in OnStop()