Friday, September 3, 2010

Interruptable Background Processing in C#

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

/*Initialises the processing controller, process events
 and starts the process.*/
public static WaitHandle[] InitialiseServiceProcess(
BackgroundWorker bg)
{
 var processSvc = new InterruptableBGProcess(bg);
 var thread = new Thread(processSvc.ProcessController);
 thread.Start();
 return new[] { 
    processSvc.SignalProcessToStop, processSvc.ProcessHasCompleted };
}


/* when thread runs... */
private void ProcessController()
{
/* wait on the threads SignalProcessToStop event*/
var wh = new WaitHandle[] { SignalProcessToStop };
while (true)
{
 /* SignalProcessToStop.Set(); 
 if above is done (i.e  set) than waitHandles will not 
receive the signal and loop will break;*/

var fTimedOut = !WaitHandle.WaitAll(wh, 100);
if (fTimedOut && counter != 100)
/* if we timed out, do the processing or 
   work not finished completely*/
  ExecuteWork(); 
else
{
  break; /* thread process was signalled to stop*/
}
}
/* indicate the processing service has stopped, allows 
waiting threads to proceed, if don't set this than main thread 
will not proceed.*/            
ProcessHasCompleted.Set();
}



Download complete example from here: Downlaod Demo InterruptableBackGroundProcessing.rar

No comments:

Post a Comment

Heroku Custom Trust Store for SSL Handshake

  Working with Heroku for deploying apps (java, nodejs, etc..) is made very easy but while integrating one of the service ho...