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

  • Home
  • SEARCH
  • 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 1039217
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T15:04:20+00:00 2026-05-16T15:04:20+00:00

I have a thread, which creates a variable number of worker threads and distributes

  • 0

I have a thread, which creates a variable number of worker threads and distributes tasks between them. This is solved by passing the threads a TaskQueue object, whose implementation you will see below.

These worker threads simply iterate over the TaskQueue object they were given, executing each task.

private class TaskQueue : IEnumerable<Task>
{
    public int Count
    {
        get
        {
            lock(this.tasks)
            {
                return this.tasks.Count;
            }
        }
    }

    private readonly Queue<Task> tasks = new Queue<Task>();
    private readonly AutoResetEvent taskWaitHandle = new AutoResetEvent(false);

    private bool isFinishing = false;
    private bool isFinished = false;

    public void Enqueue(Task task)
    {
        Log.Trace("Entering Enqueue, lock...");
        lock(this.tasks)
        {
            Log.Trace("Adding task, current count = {0}...", Count);
            this.tasks.Enqueue(task);

            if (Count == 1)
            {
                Log.Trace("Count = 1, so setting the wait handle...");
                this.taskWaitHandle.Set();
            }
        }
        Log.Trace("Exiting enqueue...");
    }

    public Task Dequeue()
    {
        Log.Trace("Entering Dequeue...");
        if (Count == 0)
        {
            if (this.isFinishing)
            {
                Log.Trace("Finishing (before waiting) - isCompleted set, returning empty task.");
                this.isFinished = true;
                return new Task();
            }

            Log.Trace("Count = 0, lets wait for a task...");
            this.taskWaitHandle.WaitOne();
            Log.Trace("Wait handle let us through, Count = {0}, IsFinishing = {1}, Returned = {2}", Count, this.isFinishing);

            if(this.isFinishing)
            {
                Log.Trace("Finishing - isCompleted set, returning empty task.");
                this.isFinished = true;
                return new Task();
            }
        }

        Log.Trace("Entering task lock...");
        lock(this.tasks)
        {
            Log.Trace("Entered task lock, about to dequeue next item, Count = {0}", Count);
            return this.tasks.Dequeue();
        }
    }

    public void Finish()
    {
        Log.Trace("Setting TaskQueue state to isFinishing = true and setting wait handle...");
        this.isFinishing = true;

        if (Count == 0)
        {
            this.taskWaitHandle.Set();
        }
    }

    public IEnumerator<Task> GetEnumerator()
    {
        while(true)
        {
            Task t = Dequeue();
            if(this.isFinished)
            {
                yield break;
            }

            yield return t;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

As you can see, I’m using an AutoResetEvent object to make sure that the worker threads don’t exit prematurely, i.e. before getting any tasks.

In a nutshell:

  • the main thread assigns a task to a thread by Enqeueue-ing a task to its TaskQueue
  • the main thread notifies the thread that are no more tasks to execute by calling the TaskQueue’s Finish() method
  • the worker thread retrieves the next task assigned to it by calling the TaskQueue’s Dequeue() method

The problem is that the Dequeue() method often throws an InvalidOperationException, saying that the Queue is empty. As you can see I added some logging, and it turns out, that the AutoResetEvent doesn’t block the Dequeue(), even though there were no calls to its Set() method.

As I understand it, calling AutoResetEvent.Set() will allow a waiting thread to proceed (who previously called AutoResetEvent.WaitOne()), and then automatically calls AutoResetEvent.Reset(), blocking the next waiter.

So what can be wrong? Did I get something wrong? Do I have an error somewhere?
I’m sitting above this for 3 hours now, but I cannot figure out what’s wrong.
Please help me!

Thank you very much!

  • 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-05-16T15:04:21+00:00Added an answer on May 16, 2026 at 3:04 pm

    Your dequeue code is incorrect. You check the Count under lock, then fly by the seams of your pants, and then you expect the tasks to have something. You cannot retain assumptions while you release the lock :). Your Count check and tasks.Dequeue must occur under lock:

    bool TryDequeue(out Tasks task)
    {
      task = null;
      lock (this.tasks) {
        if (0 < tasks.Count) {
          task = tasks.Dequeue();
        }
      }
      if (null == task) {
        Log.Trace ("Queue was empty");
      }
      return null != task;
     }
    

    You Enqueue() code is similarly riddled with problems. Your Enqueue/Dequeue don’t ensure progress (you will have dequeue threads blocked waiting even though there are items in the queue). Your signature of Enqueue() is wrong. Overall your post is very very poor code. Frankly, I think you’re trying to chew more than you can bite here… Oh, and never log under lock.

    I strongly suggest you just use ConcurrentQueue.

    If you don’t have access to .Net 4.0 here is an implementation to get you started:

    public class ConcurrentQueue<T>:IEnumerable<T>
    {
        volatile bool fFinished = false;
        ManualResetEvent eventAdded = new ManualResetEvent(false);
        private Queue<T> queue = new Queue<T>();
        private object syncRoot = new object();
    
        public void SetFinished()
        {
            lock (syncRoot)
            {
                fFinished = true;
                eventAdded.Set();
            }
        }
    
        public void Enqueue(T t)
        {
            Debug.Assert (false == fFinished);
            lock (syncRoot)
            {
                queue.Enqueue(t);
                eventAdded.Set();
            }
        }
    
        private bool Dequeue(out T t)
        {
            do
            {
                lock (syncRoot)
                {
                    if (0 < queue.Count)
                    {
                        t = queue.Dequeue();
                        return true;
                    }
                    if (false == fFinished)
                    {
                        eventAdded.Reset ();
                    }
                }
                if (false == fFinished)
                {
                    eventAdded.WaitOne();
                }
                else
                {
                    break;
                }
            } while (true);
            t = default(T);
            return false;
        }
    
    
        public IEnumerator<T> GetEnumerator()
        {
            T t;
            while (Dequeue(out t))
            {
                yield return t;
            }
        }
    
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 515k
  • Answers 515k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer >>> import time >>> timestamp = 1284375159 >>> time.strftime("%m %d… May 16, 2026 at 6:31 pm
  • Editorial Team
    Editorial Team added an answer From a little FAQ chapter to the release: The standard… May 16, 2026 at 6:31 pm
  • Editorial Team
    Editorial Team added an answer Not a language per se, but analog computers are in… May 16, 2026 at 6:31 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

I have a main program which creates a collection of N child threads to
I have a modelless dialog that creates a thread, and if the cancel button
being new to c# I've run into this 'conundrum' when passing around a SqlDataReader
I have the following script, which is working for the most part Link to
In general, if you have a class that inherits from a Thread class, and
i have a problem with the order of execution of the threads created consecutively.
When I have made simple single thread games I implemented the game logic in
I have 2 threads running in paralel. The run function of the threads is
I have been reading a lot about Reinforcement Learning lately, and I have found
in my application there is a small part of function,in which it will read

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.