Greetings (Derivation version)
The second "Hello, world" example program. This class runs a simple
simulation that prints a greeting message to standard output (e.g. the
console). In this example, the main class is derived from the
Process
class. The GetProcessSteps
method is overridden to provide the code which prints the greeting message.
The complete code for this example is shown below and is also available as greetings2.cs in the examples\greetings directory.
using System; using System.Collections.Generic; using React; public class Greetings : React.Process { private Greetings(Simulation sim) : base(sim) { } protected override IEnumerator<Task> GetProcessSteps() { Console.WriteLine("Greetings2 says, Hello there ..."); yield return Delay(1000); yield break; } public static void Main(string [] args) { Simulation sim = new Simulation(); sim.Run(new Greetings(sim)); } }
The Explanation
Start by including references to some of the required namespaces. The
System.Collections.Generic
namespace is required for the
IEnumerator<Task>
class. The React
namespace is required for the Simulation
, Task
,
and Process
classes.
using System; using System.Collections.Generic; using React;
The Greetings class is derived from React.Process
and
contains a private constructor to prevent other classes from instantiating
it.
public class Greetings : React.Process { private Greetings(Simulation sim) : base(sim) { } . . . }
The overridden GetProcessSteps method defines the functionality of the
Greetings object that will be created in the Main method. GetProcessSteps
is the iterator method used by the Greetings object to yield its Tasks. As
a change from version #1, GetProcessSteps yields a Task
, specifically
a Delay task, via the yield return Delay(1000);
statement.
The delay causes 1000 time units to pass. Including the yield break;
statement allows us to delete the delay while maintaining GetProcessSteps
as a .NET iterator.
protected override IEnumerator<Task> GetProcessSteps() { Console.WriteLine("Greetings2 says, Hello there ..."); yield return Delay(1000); yield break; }
Finally, the Main method instantiates a Simulation object and
calls the Run
method passing it a new Greetings object.
Since Greetings is a Process, it serves as the Simulation's
generator task.
Simulation sim = new Simulation(); sim.Run(new Greetings(sim));