Friday, September 3, 2010

I was looking for some Interruptable background processing utility in C#.

Background processing can be done with BackgroundWorker but making it interruptable
was the tricky one. Its not only the threading but handling the events too.

Tried to google it did not find the exact one but some good help.

On any activity (user stops the process or work completes ) signal shall be raised to process the main thread.

Doing the process of actual work can be started in the Thread or Worker Thread in the background asynchronously.
Starting Thread ( in InterruptableBGProcess.InitialiseServiceProcess(...))
in the background.

InterruptableBGProcessing.cs

void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
isStopped = false;
/* initialise the background processing service */
var serviceControlEvents = InterruptableBGProcess.InitialiseServiceProcess((BackgroundWorker)sender);
/* now simulate a waitstate by waiting until the user click on stop orwork completed. */
while (true)
{
if (isStopped || ProgressBar.Value == 100)
{
break;
}
}
/* signal the event to tell the service to stop, then wait for the event
to be set which indicates the service has stopped*/
WaitHandle.SignalAndWait(serviceControlEvents[0], serviceControlEvents[1]);
}

Once thread started it will look for the event signals
SignalProcessToStop and ProcessHasCompleted of type AutoResetEvent