Long running code |
Previous section: The code editor window in detail
This topic contains the following sections:
Long running code in Altaxo is code that runs for more than 10 seconds. If your code runs for more than 10 seconds, another dialog box will open, which allows you to cancel or interrupt code execution. You can help to make long running code a little bit more responsive.
There is a variable reporter available in the Execute method (Execute is the default method of the worksheet script). The reporter variable can and should be used for the following two purposes:
To allow the user to cancel execution, and to return from code execution in a defined state.
To show the user the progress of your code execution.
To allow the user to cancel long running code, look at the following example:
for (int i = 0; i < 100000; i++) { Foo(); // method Foo() runs moderately long (say < 1 s) if (reporter.CancellationPending) break; // or: return }
Here, the if (reporter.CancellationPending) statement ask the reporter if the user has requested to cancel the execution, and if so, ends the loop with a break statement.
The example above can be extended to show progress to the user.
int len = 100000; for (int i = 0; i < len; i++) { Foo(); // method foo runs moderately long (< 1 s) if (reporter.CancellationPending) break; // or: return if (reporter.ShouldReportNow) reporter.ReportProgress(string.Format("{0} of {1}", i, len), i / (double)len); }
Here, the statement if (reporter.ShouldReportNow) first asks if it is necessary to report now (this property is set every second or so). If so, the method ReportProgress is called, which reports the progress both as text (string.Format...) as well as as a numerical value in the range from 0 to 1. This value is calculated using the loop variable i and dividing it to the total number of loops len.
Of course, you can omit the if (reporter.ShouldReportNow) statement and directly call the ReportProgress method. For smaller loops this is OK, but for a loop as shown here, this would call the string.Format method and ReportProgress method a hundred thousand times. Not very effective!
Next section: Project organization