Antony
Antony

Reputation: 1461

Gracefully stop a Timer callback worker thread

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?

Upvotes: 2

Views: 1453

Answers (2)

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19956

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:

bool shouldAbort=false;

TimerProc()
{
     Step1();
     if (shouldAbort)
     {
         UndoStep1();
         return;
     }
     Step2();
     if (shouldAbort)
     {
         UndoStep2();
         UndoStep1();  //  or vice versa, depending on your operations
         return;
     }
     // ...
}

in OnStop()

timer.Stop();  //  don't worry here - your TimerProc() WILL finish
shouldAbort=true;

Upvotes: 1

SamStephens
SamStephens

Reputation: 5861

You could look at using the Task Parallel Library. Have a read of the Task Cancellation page. This would give you a way to create worker threads that can tidy up cleanly in response to a cancellation, if I've understood your needs correctly.

Upvotes: 0

Related Questions