Time for action – dealing with cancellation

Sometimes the user will change their mind; they may have selected the wrong option, or something more important may have come up. The progress monitor allows for two-way communication; the user can signify when they want to cancel as well. There is a method, isCancelled, which returns true if the user has signified in some way that they want the job to finish early.

Periodically checking this during the operation of the Job allows the user to cancel a long-running job before it reaches the end.

  1. Modify the for loop in the HelloHandler to check on each iteration whether the monitor is cancelled:
    for (int i = 0; i < 50 && !monitor.isCanceled(); i++) {
      ...
    }
    if (!monitor.isCancelled()) {
      display.asyncExec(() -> {...});
    }
  2. Run the Eclipse instance and click on the Hello command. This time, go into the Progress view and click on the red stop square next to the job; the job should cancel and the dialog showing the message shouldn't be shown:
    Time for action – dealing with cancellation

What just happened?

Being responsive to the user is a key point in implementing plug-ins. If there are long-running operations, make sure to check whether the user has cancelled the operation—there's no point in tying up the CPU if the user doesn't want it to continue.

The monitor.isCancelled call is generally implemented with a single field access, so calling it frequently often has no negative performance implications. Calling the isCancelled method too much is never noticed by users; however, not calling it enough certainly is noticed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.98.13