Canceling synchronous algorithms

In order to provide responsiveness and cancelability for long running operations, in general all applications should give the user the opportunity to cancel an algorithm. Commonly this need arises when graphical user interfaces are used and is solved by running the algorithm in a seperate thread. For graphical user interfaces one might use the ILAsyncAlgorithm class to profit from its capabilities of running in a seperate thread and inter thread communication for state signaling. See using asynchronous algorithms in ILNumerics.Net for a description of this class.

This article describes the ablity of synchronous algorithms to react on cancellation requests. ILAlgorithm derived classes always execute synchronously. Therfore no multithreading is involved. However, the algorithm may has to be stopped depending on a distinct progress value or on the precision of the achieved result. The cancellation is that way triggered somehow deterministically by the calling function.

How does cancellation for synchronous algorithms work?

Whenever an event gets fired from an ILAlgorithm class, it carries a flag bool cancel, which the receiver of the event may set to true in order to request a cancellation.

Example (C#)
void myAlgorithm_ProgressChanged(object sender, ILAlgorithmEventArgs e) {
  // check the cancellation condition programmatically
  if (e.Progress > 0.85) {
    // trigger cancellation of the algorithm
    e.Cancel = true;
  }
}

For a developer of the synchronous algorithm it is important to check the return value from the functions SetState and (moreover) SetProgress whenever called. If the method returns true, the algorithm should keep on going, if it returns false, a cancellation has been requested.

Synchronous algorithms will mostly use eventing only for informing the implementor of its state. Use the ILAsyncAlgorithm class described here if you wish to support cancellation and multi-threading at runtime!


Valid CSS! Valid XHTML 1.0 Transitional