Greetings (Delegate version)
This is the first "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, none of the React.NET classes are subclassed to implement the simulation. The process steps are provided via a delegate, SayHello.
This example program demonstrates how a simple simulation can be created
without extending any of the React.NET classes. Most simulations will
probably contain subclasses of the Process
class and
possibly of the Simulation
class.
The complete code for this example is shown below and is also available as greetings1.cs in the examples\greetings directory.
using System; using System.Collections.Generic; using React; public class Greetings { private Greetings() { } private IEnumerator<Task> SayHello(Process process, object data) { Console.WriteLine("Greetings1 says, Hello there ..."); yield break; } public static void Main(string [] args) { Simulation sim = new Simulation(); Greetings greetings = new Greetings(); Process process = new Process(sim, greetings.SayHello); sim.Run(process); } }
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 System.Object
and
contains a private constructor to prevent other classes from instantiating
it.
public class Greetings { private Greetings() { } . . . }
The private SayHello method defines the functionality of the Process that will be created in the Main method. SayHello is the delegate used by the Process to yield its Tasks. Of course, in this case, all the Process will do is print a message and exit -- no Tasks are returned by SayHello.
The yield break;
statement must be included or SayHello
will not be a valid .NET iterator.
private IEnumerator<Task> SayHello(Process process, object data) { Console.WriteLine("Greetings1 says, Hello there ..."); yield break; }
Finally, the Main method instantiates a Simulation object and
a Greetings object. A new Process is created passing the constructor
the SayHello delegate. The new process is passed to the
Run method of the Simulation class to serve as the generator
task which is executed by the Simulation, sim
. When the
generator task is executed, the SayHello method will get called and
the greetings message printed to the console.
Simulation sim = new Simulation(); Greetings greetings = new Greetings(); Process process = new Process(sim, greetings.SayHello); sim.Run(process);