Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8519989
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T06:24:24+00:00 2026-06-11T06:24:24+00:00

I have multiple tasks in an array, that are used to compute prime numbers

  • 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;
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T06:24:26+00:00Added an answer on June 11, 2026 at 6:24 am

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Capistrano deploy.rb script which has multiple tasks that can be invoked
I have multiple Java tasks that access solr and write and commit some documents
I have a counter that's used by multiple threads to write to a specific
I have multiple Users, each with a collection of Tasks. public class User {
My goal is to have an AsyncTask that can execute multiple times (one task
We have 10 Linux boxes that must run 100 different tasks each week. These
I'm making a task-based program that needs to have plugins. Tasks need to have
i have multiple cronjobs that are setup as define: 0 1 * * *
I need to write an application in c# that keeps track of multiple tasks,
I'm working on a Java project where I need to have multiple tasks running

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.