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 9212271
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T01:29:10+00:00 2026-06-18T01:29:10+00:00

Requirement :- At any given point of time only 4 threads should be calling

  • 0

Requirement :- At any given point of time only 4 threads should be calling four different functions. As soon as these threads complete, next available thread should call the same functions.

Current code :- This seems to be the worst possible way to achieve something like this. While(True) will cause unnecessary CPU spikes and i could see CPU rising to 70% when running the following code.

Question :- How can i use AutoResetEventHandler to signal Main thread Process() function to start next 4 threads again once the first 4 worker threads are done processing without wasting CPU cycles. Please suggest

public class Demo
{
    object protect = new object();
    private int counter;
    public void Process()
    {
        int maxthread = 4;
        while (true)
        {
            if (counter <= maxthread)
            {
                counter++;
                Thread t = new Thread(new ThreadStart(DoSomething));
                t.Start();
            }
        }
    }
    private void DoSomething()
    {
        try
        {
            Thread.Sleep(50000); //simulate long running process
        }
        finally
        {
            lock (protect)
            {
                counter--;
            }
        }
    }
  • 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-18T01:29:12+00:00Added an answer on June 18, 2026 at 1:29 am

    You can use TPL to achieve what you want in a simpler way. If you run the code below you’ll notice that an entry is written after each thread terminates and only after all four threads terminate the "Finished batch" entry is written.

    This sample uses the Task.WaitAll to wait for the completion of all tasks. The code uses an infinite loop for illustration purposes only, you should calculate the hasPendingWork condition based on your requirements so that you only start a new batch of tasks if required.

    For example:

    private static void Main(string[] args)
    {
        bool hasPendingWork = true;
        do
        {
            var tasks = InitiateTasks();
    
            Task.WaitAll(tasks);
    
            Console.WriteLine("Finished batch...");
        } while (hasPendingWork);
    }
    
    private static Task[] InitiateTasks()
    {
        var tasks = new Task[4];
    
        for (int i = 0; i < tasks.Length; i++)
        {
            int wait = 1000*i;
    
            tasks[i] = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(wait);
                Console.WriteLine("Finished waiting: {0}", wait);
            });
        }
    
        return tasks;
    }
    

    One other thing, from the textual requirement section on your question I’m lead to believe that a batch of four new threads should only start after all previously four threads completed. However the code you posted is not compatible with that requirement, since it starts a new thread immediately after a previous thread terminate. You should clarify what exactly is your requirement.


    UPDATE:

    If you want to start a thread immediately after one of the four threads terminate you can still use TPL instead of starting new threads explicitly but you can limit the number of running threads to four by using a SemaphoreSlim. For example:

    private static SemaphoreSlim TaskController = new SemaphoreSlim(4);
    
    private static void Main(string[] args)
    {
        var random = new Random(570);
    
        while (true)
        {
            // Blocks thread without wasting CPU
            // if the number of resources (4) is exhausted
            TaskController.Wait();
    
            Task.Factory.StartNew(() =>
            {
                Console.WriteLine("Started");
                Thread.Sleep(random.Next(1000, 3000));
                Console.WriteLine("Completed");
                // Releases a resource meaning TaskController.Wait will unblock
                TaskController.Release();
            });
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've a requirement to serialize any class provided (decorated with the appropriate XmlElement/ XmlAttribute
Can anyone please tell me is there any special requirement to use either EXTERN
I have a simple requirement as mentioned below: A ListView or any control displays
I have a requirement where i have to update a textbox if any of
I have a requirement: I want to call method every day at any particular
Is there any way to pre compile stored procedures in SQL Server? My requirement
I have researched enough on this topic sans any luck :-( My requirement is
Please tell me any one, how to kill previous stacked activity.My requirement is like
I'm stuck with the following scenario and appreciate any help/advice.. Requirement I have number
I have a datatable being built in code which can dynamically have any given

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.