This tutorial gives a step by step narrative for creating an example application. The application built throughout this section is a pi calculator that uses the dartboard algorithm.

The tutorial assumes usage of either the Embedded Job Scheduler or a Coordinator running with a registered Agent. For instructions on setting up an environment see the Getting Started document.

In this section the following is explained:

Creating Task class

The very first step is defining a task. A task represents the code that will run. User defined tasks must derive from Task. Tasks are required to be serialized by .NET's BinaryFormatter. A way to do this is to add SerializableAttribute to the Task class. The most important aspect of writing the Task class is overriding the Execute()()()() method. This Execute method is the entry point into the Task.

For this pi calculator, the Execute method of the task contains the logic of the dartboard algorithm. Here is the code:

C#  Copy imageCopy
[Serializable]
public class PiDartboardAlgorithmTask : Task
{
    private int dartsPerTask;

    public PiDartboardAlgorithmTask(int dartsPerTask)
    {
        this.dartsPerTask = dartsPerTask;
    }

    public override void Execute()
    {
        Random random = new Random(System.Diagnostics.Process.GetCurrentProcess().Id + Environment.TickCount);
        int numDartsInCircle = 0;

        for (int i = 0; i < dartsPerTask; i++)
        {
            double x = (random.NextDouble() - 0.5) * 2;
            double y = (random.NextDouble() - 0.5) * 2;
            if ((x * x) + (y * y) <= 1.0)
            {
                numDartsInCircle++;
            }
        }

        this.Result = numDartsInCircle;
    }
}

Connect to the job scheduler

Connecting to the Coordinator consists of one line. The hostname is the DNS name or IP address of the Coordinator. If the coordinator is not running on the default port (9090), also specify the port number. The Connect()()()() method must be called before any of the operations on the coordinator can be performed.

C#  Copy imageCopy
IJobScheduler scheduler = new ClusterJobScheduler("localhost");
scheduler.Connect();

For EmbeddedJobScheduler, the code is similar:

C#  Copy imageCopy
IJobScheduler scheduler = new EmbeddedJobScheduler();
scheduler.Connect();

Once Connect is successfully called, call Dispose()()()() on the client when it is no longer needed. Otherwise, unnecessary coordinator resources will be consumed and the application may not exit properly. Alternatively, declare and instantiate the job scheduler within a using statement to ensure it is properly disposed of.

Note

If an exception is thrown at the Connect method and says something like "Cannot connect to Coordinator", the most likely reason is that the Coordinator is not running on the specified machine and port. Make sure coordinator is running on that machine and confirm a firewall is not blocking the port.

Cluster Connect Exception

Submit Job

After connecting to the coordinator, specify tasks to submit. First, create a Job using CreateJob()()()(). Next, instantiate the Task(s) written above. Add the tasks to the Job using AddTask(Task).

For the pi calculator, add multiple tasks to the job to get more samples. When finished adding tasks, the Submit()()()() method will actually submit the job to the coordinator.

Note

The are also many options on the job that you could specify. For this tutorial, you will just use two of the options, Name and Description.

The pi calculator submit code should look like this:

C#  Copy imageCopy
int numDartsPerTask = 1000000;
int numTasks = 8;

Job job = scheduler.CreateJob();
job.Name = "PiJob";
job.Description = "Computes digits of PI using dartboard algorithm.";

for (int i = 0; i < numTasks; i++)
{
    job.AddTask(new PiDartboardAlgorithmTask(numDartsPerTask));
}

job.Submit();

Waiting for task results

Calling WaitUntilDone()()()() will block the current thread until all of the job's tasks are completed. Once the job is completed, the result of each task is sent back to the client. One of the results you can get from the task is from the Result property.

For the pi calculator, you want to sum up the task's result. The WaitUntilDone code will look like this:

C#  Copy imageCopy
job.WaitUntilDone();

int sumOfDarts = 0;
for (int i = 0; i < numTasks; i++)
{
    sumOfDarts += (int)job.Tasks[i].Result;
}

Console.WriteLine("PI is approximately {0:F15}", (4.0 * (double)sumOfDarts) / (numDartsPerTask * numTasks));

// Make sure you Dispose the scheduler after you are done.
scheduler.Dispose();

The complete application

Here is the complete application after all the steps are applied:

C#  Copy imageCopy
using System;
using AGI.Parallel.Client;
using AGI.Parallel.Infrastructure;

namespace CodeSamples
{
    class Program
    {
        static void Main(string[] args)
        {
            IJobScheduler scheduler = new ClusterJobScheduler("localhost");
            scheduler.Connect();

            int numDartsPerTask = 1000000;
            int numTasks = 8;

            Job job = scheduler.CreateJob();
            job.Name = "PiJob";
            job.Description = "Computes digits of PI using dartboard algorithm.";

            for (int i = 0; i < numTasks; i++)
            {
                job.AddTask(new PiDartboardAlgorithmTask(numDartsPerTask));
            }

            job.Submit();

            job.WaitUntilDone();

            int sumOfDarts = 0;
            for (int i = 0; i < numTasks; i++)
            {
                sumOfDarts += (int)job.Tasks[i].Result;
            }

            Console.WriteLine("PI is approximately {0:F15}", (4.0 * (double)sumOfDarts) / (numDartsPerTask * numTasks));

            // Make sure you Dispose the scheduler after you are done.
            scheduler.Dispose();
        }
    }

    [Serializable]
    public class PiDartboardAlgorithmTask : Task
    {
        private int dartsPerTask;

        public PiDartboardAlgorithmTask(int dartsPerTask)
        {
            this.dartsPerTask = dartsPerTask;
        }

        public override void Execute()
        {
            Random random = new Random(System.Diagnostics.Process.GetCurrentProcess().Id + Environment.TickCount);
            int numDartsInCircle = 0;

            for (int i = 0; i < dartsPerTask; i++)
            {
                double x = (random.NextDouble() - 0.5) * 2;
                double y = (random.NextDouble() - 0.5) * 2;
                if ((x * x) + (y * y) <= 1.0)
                {
                    numDartsInCircle++;
                }
            }

            this.Result = numDartsInCircle;
        }
    }
}

Next Steps

With an example application completed, explore other concepts at Key concepts or review the Library Reference.

See Also