0

I have multiple tasks in an array, that are used to compute prime numbers in a given range. To undergo a comparison of tasks vs thread performance, I want to use threads within tasks and then check the performance stats.

How will the threads be used with tasks, so far this is what I have done:

public Form1()
    {
        InitializeComponent();

        cpuCounter = new PerformanceCounter();

        cpuCounter.CategoryName = "Processor";
        cpuCounter.CounterName = "% Processor Time";
        cpuCounter.InstanceName = "_Total";

        ramCounter = new PerformanceCounter("Memory", "Available MBytes");

        this.scheduler = TaskScheduler.FromCurrentSynchronizationContext();

        this.numericUpDown1.Maximum = int.MaxValue;
    }

    private void btnCalculate_Click(object sender, EventArgs e)
    {
        //get the lower and upper bounds for prime range
        int lower = int.Parse(this.numericUpDown1.Value.ToString());
        int upper = 0 ;

        //get the time in milliseconds for task deadline
        int taskDeadline = int.Parse(this.time.Text);

        //determine tasks completed
        int tasksCompleted = 0;

        Random random = new Random();

        for (int taskCount = 1; taskCount <= 1; ++taskCount)
        {
            int taskArraySize = taskCount * 100;
            Task[] taskArray = new Task[taskArraySize];

            this.txtNumOfPrimes.Text += "Performing test for " +  
                 taskArraySize.ToString() + 
                 " tasks" + 
                 Environment.NewLine + 
                 Environment.NewLine; 

            for (int i = 0; i < taskArray.Length; i++)
            {
                upper = random.Next(5, 10);
                taskArray[i] = new Task(() => getPrimesInRange(lower, upper));
                taskArray[i].Start();

                bool timeout = taskArray[i].Wait(taskDeadline);

                if (!timeout)
                {
                    // If it hasn't finished at timeout display message
                    this.txtNumOfPrimes.Text += 
                        "Message to User: Task not completed, Status=> " + 
                        taskArray[i].Status.ToString() + 
                        Environment.NewLine;

                }

                else
                {
                    this.txtNumOfPrimes.Text += "Task completed in timeout " + 
                         ", CPU usage: " + this.getCurrentCpuUsage() + 
                         ", RAM usage: " + 
                         this.getAvailableRAM() + 
                         Environment.NewLine;

                    tasksCompleted++;
                }
            }
        }



        this.txtNumOfPrimes.Text += Environment.NewLine;
        this.txtNumOfPrimes.Text += 
            "Tasks Completed: " + 
            tasksCompleted.ToString() + 
            Environment.NewLine;
    }
Shakti Prakash Singh
  • 2,414
  • 5
  • 35
  • 59
faizanjehangir
  • 2,771
  • 6
  • 45
  • 83
  • 1
    "threads within tasks" or "threads instead of tasks" ? The first seems illogical. – H H Sep 12 '12 at 11:37
  • i do not want to replace tasks with threads..I want to do the task with the help of threads. – faizanjehangir Sep 12 '12 at 11:40
  • 1
    You fundamentally misunderstand how tasks work. This can't be addressed in an SO post, it fails the "If you can imagine an entire book that answers your question, you’re asking too much" FAQ entry. You'll need to educate yourself, there are plenty of good books and tutorials available. – Hans Passant Sep 12 '12 at 11:54

1 Answers1

1

The whole point of tasks is "simplifying the process of adding parallelism and concurrency to applications". Indeed (from http://msdn.microsoft.com/en-us/library/dd537609):

Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with algorithms (like hill-climbing) that determine and adjust to the number of threads that maximizes throughput. This makes tasks relatively lightweight, and you can create many of them to enable fine-grained parallelism. To complement this, widely-known work-stealing algorithms are employed to provide load-balancing.

In short, tasks do the thread work without much of the hassle and legwork.

To compare the two, consider using Parrallel.ForEach for tasks. For example:

public class PrimeRange
{
    public int Start;
    public int Snd;
}

List<PrimeRange> primes = new []
{
    new PrimeRange{Start = 0, End = 1000},
    new PrimeRange{Start = 1001, End = 2000}
    // An so on
};
Parallel.ForEach(primes, x => CalculatePrimes(x, OnResult())));

where CalculatePrimes is a method that takes a PrimeRange and a delegate to call when the primes have been calculated. Parraler.ForEach will start a task for each element of primes and run CalculatePrimes() on it and handle the thread assignment and scheduling for you.

To compare it to threads, use something like:

List<Thread> threads = new List<Thread>();
foreach(PrimeRange primeRange in primes)
{
    threads = new Thread(CalculatePrimes).Start(x);
}
foreach(var thread in threads)
{
    thread.Join();
}    

where CalculatePrimes would need to also store the results (or something similar). See C# Waiting for multiple threads to finish for more information about waiting on running threads.

You could time the results using a StopWatch.

Community
  • 1
  • 1
akton
  • 14,148
  • 3
  • 43
  • 47
  • @HenkHolterman It was coming. I just wanted to get some base information first. – akton Sep 12 '12 at 11:54
  • Ok, So in order to continue with the comparison, do I need to use parallel execution of tasks like you suggested, or do I have to assign threads explicitly? – faizanjehangir Sep 12 '12 at 11:57
  • @faizanjehangir The tasks library assigns tasks to threads automatically. It also ensures the CPU is not overloaded with too many tasks and, when using async/await, can even shift tasks in and out of threads. Admittedly, you can use a `ThreadPool` (http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx) to do some of this. – akton Sep 12 '12 at 12:01
  • @akton Thank you, the post really helped me in understanding. Will surely give it a thorough reading and experimentation for better understanding. – faizanjehangir Sep 12 '12 at 12:03