Terminate a task
You can terminate a task at runtime. You cannot run a terminated task.
Stop() method
Stop()
methodEach asynchronous task automatically terminates when the NetLogic parent node is removed. Nevertheless, we recommend to explicitly terminate tasks inside the
Stop()
method by invoking the Dispose()
method, as shown in the following example.
public override void Stop() { myTask.Dispose(); }
IMPORTANT:
Invoking the
Dispose()
method on an asynchronous task blocks it until the code ran by the task returns the control to the caller (through control of the task state or for completion of the task).Example
The following example shows creating, running, and terminating an asynchronous task.
public override void Start() { myTask = new PeriodicTask(IncrementVariable, 1000, LogicObject) myTask.Start(); } public override void Stop() { myTask.Dispose(); } private void IncrementVariable() { variable1.Value = variable1.Value + 1; } private PeriodicTask myTask;
The example involves:
- Defining a private instance variable (private PeriodicTask myTask;) in the C# class contained in the NetLogic.TIP: Depending on the type of task to be created, the class of this variable must bePeriodicTask,DelayedTask, orLongRunningTask
- Defining a method (IncrementVariable()) that the task must run.
- Creating the task.Inside theStart()method, in the C# class contained in the NetLogic, the private instance variable (myTask) is initialized using the class constructor (PeriodicTask).TIP: The constructor requires a variety of arguments based on the class to which it belongs. See Asynchronous task.
- Executing the task as soon as the NetLogic is initialized at runtime.Inside theStart()method in the C# class contained in the NetLogic, theStart()method is invoked on the task (myTask.Start()).
- Terminating the task in theStop()method by invoking theDispose()method.
Provide Feedback