Execution
constraints give you the possibility to monitor whether a certain
operation is completed within a determined amount of time. The
execution time is monitored by a background thread. After an operation
is completed, the monitoring is stopped by uninstalling the execution
constraint.
Execution constraints are represented by the Microsoft.SPOT.ExecutionConstraint class. You can install and activate an execution constraint with the static method Install. The Install method expects the greatest acceptable amount of time in milliseconds. Additionally, the priority
integer parameter specifies a thread priority. This parameter does not
seem to be used, however, by the runtime environment, thus you can pass
0 here confidently.
After completion of the monitored operation, you need to uninstall the execution constraint by calling the method Install with −1 for the timeout parameter.
If the monitored operation lasts longer than was forced, Microsoft.SPOT.ConstraintException
is thrown. The elapsed time is not analyzed when the execution
constraints are uninstalled, but the background thread throws the
exception immediately on expiration of the forced time.
The example in Listing 9-6
demonstrates the use of execution constraints. Two operations are
checked. Both operations must be completed in a maximum of 100
milliseconds. Like the operations, Thread.Sleep is executed once within 50 milliseconds and once within 100 milliseconds.
The
first operation is executed successfully within the permitted time, and
the debug message is put out. For the second operation, a ConstraintException is thrown.
Example 1. Using Execution Contraints
using System; using Microsoft.SPOT; using System.Threading;
namespace ExecutionConstraintSample { public class Program { public static void Main() { const int timeout = 100; // 100 ms = max. accepted duration of operation
ExecutionConstraint.Install(timeout, 0); //install to check constraint //do something which must take less than timeout Thread.Sleep(50); //operation is executed in less time //end of operation ExecutionConstraint.Install(-1, 0); //uninstall Debug.Print("First operation successfully executed.");
ExecutionConstraint.Install(timeout, 0); //install to check constraint //do something which must take less than timeout //operation takes longer as forced, //so an exception will be thrown after timeout ms Thread.Sleep(150); //end of operation ExecutionConstraint.Install(-1, 0); //uninstall Debug.Print("Second operation successfully executed."); } } }
|
Execution constraints (and Listing 9-6)
do not work as expected in version 2.5 of the .NET Micro Framework,
though they work fine with version 2.0. This error is supposed to be
fixed with a service pack for version 2.5.
|
|