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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T21:56:22+00:00 2026-05-26T21:56:22+00:00

Working on .net 2.0 I need to implement the some threading and I was

  • 0

Working on .net 2.0 I need to implement the some threading and I was looking at a dummy examples but cannot find anything which implement eventnotification.
Need to know when all is done and also some sort of progress bar if you like.

I am been playing with following code by cannot see to get the event notification correctly.
How do I detect that I have finished the processing and possible updating the ui with what I have been doing?

Example code

 class Program
{
    static void Main(string[] args)
    {
        using (PCQueue q = new PCQueue(2))
        {
            q.TaskCompleted += new EventHandler(OnTaskCompleted);
            q.PercentageCompleted += new EventHandler(OnPercentageCompleted);


            for (int i = 1; i < 100; i++)
            {

                string itemNumber = i.ToString(); // To avoid the captured variable trap
                q.EnqueueItem(itemNumber);
            }
          Console.WriteLine("Waiting for items to complete...");
            Console.Read();
        }
    }

    private static void OnPercentageCompleted(object sender, EventArgs e)
    {

    }

    static void OnTaskCompleted(object sender, EventArgs e)
    {

    }
}


public class PCQueue : IDisposable
{
    readonly object locker = new object();
    Thread[] _workers;
    Queue<string> _itemQ = new Queue<string>();
    public PCQueue(int workerCount)
    {
        _workers = new Thread[workerCount];
        // Create and start a separate thread for each worker
        for (int i = 0; i < workerCount; i++)
        {
            (_workers[i] = new Thread(Consume)).Start();
        }
    }

    public void EnqueueItem(string item)
    {
        lock (locker)
        {
            _itemQ.Enqueue(item); // We must pulse because we're
            Monitor.Pulse(locker); // changing a blocking condition.
        }
    }
    void Consume()
    {
        while (true) // Keep consuming until
        { // told otherwise.
            string item;
            lock (locker)
            {
                while (_itemQ.Count == 0) Monitor.Wait(locker);
                item = _itemQ.Dequeue();
            }
            if (item == null) return; // This signals our exit.

            DoSomething(item); // Execute item.
        }
    }
    private void DoSomething(string item)
    {
       Console.WriteLine(item);
    }
    public void Dispose()
    {
        // Enqueue one null item per worker to make each exit.
        foreach (Thread worker in _workers)
        {
            EnqueueItem(null);
        }
    }

    //where/how  can I fire this event???
    public event EventHandler TaskCompleted;
    protected void OnCompleted(EventArgs e)
    {
        if (this.TaskCompleted != null)
        {
            this.TaskCompleted(this, e);
        }
    }
    //where/how can I fire this event???
    public event EventHandler PercentageCompleted;
    protected void OnPercentageCompleted(EventArgs e)
    {
        if (this.PercentageCompleted != null)
        {
            this.PercentageCompleted(this, e);
        }
    }
   }

Any suggestions?

  • 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-26T21:56:22+00:00Added an answer on May 26, 2026 at 9:56 pm

    You can’t raise the progress event inside your queue for the simple reason that the queue does not know the total number items which are supposed to be processed. So it can’t calculate a percentage. You just stick something in and it gets processed.

    What you could do is to raise a ItemProcessed event and subscribe to that. Then in your main program you can do the logic of counting how many items were processed so far in relation to how many are supposed to be processed.

    You can raise the complete event just before you are returning from your Consume function. However you need to keep track of how many threads are still active as Brian said in his answer. I modified the code to reflect that.

    So something along these lines:

    ...
    private int _ActiveThreads;
    public PCQueue(int workerCount)
    {
        _ActiveThreads = workerCount;
        _workers = new Thread[workerCount];
        // Create and start a separate thread for each worker
        for (int i = 0; i < workerCount; i++)
        {
            (_workers[i] = new Thread(Consume)).Start();
        }
    }
    
    void Consume()
    {
        while (true) // Keep consuming until
        { // told otherwise.
            string item;
            lock (locker)
            {
                while (_itemQ.Count == 0) Monitor.Wait(locker);
                item = _itemQ.Dequeue();
            }
            if (item == null)  // This signals our exit.
            {
                if (Interlocked.Decrement(ref _ActiveThreads) == 0)
                {
                    OnCompleted(EventArgs.Empty);
                }
                return;
            }
    
            DoSomething(item); // Execute item.
            OnItemProcessed();
        }
    }
    
    public event EventHandler ItemProcessed;
    protected void OnItemProcessed()
    {
        var handler = ItemProcessed;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }
    ...
    

    Of course you might want to create some meaningfull event args and actually pass the item which was processed to the event.

    Then in main:

    ...
    static void Main(string[] args)
    {
        using (PCQueue q = new PCQueue(2))
        {
            q.ItemProcessed += ItemProcessed;
            q.TaskCompleted += OnTaskCompleted;
    
            for (int i = 1; i <= totalNumberOfItems; i++)
            {
                string itemNumber = i.ToString(); // To avoid the captured variable trap
                q.EnqueueItem(itemNumber);
            }
            Console.WriteLine("Waiting for items to complete...");
            Console.Read();
        }
    }
    
    private static int currentProcessCount = 0;
    private static int totalNumberOfItems = 100;
    
    private static void ItemProcessed(object sender, EventArgs e)
    {
         currentProcessCount++;
         Console.WriteLine("Progress: {0}%", ((double)currentProcessCount / (double)totalNumberOfItems) * 100.0);
    }
    
    static void OnTaskCompleted(object sender, EventArgs e)
    {
         Console.WriteLine("Done");
    }
    ...
    

    Needless to say that all that static stuff should go. This is just based on your example.

    One more remark:
    Your PCQueue currently requires that you enqueue as many null values as you have worker threads otherwise only one thread will quit and the others will wait until your process quits. You can change that by looking at the first item and only removing it when it is not null – thus leaving the marker there for all threads. So Consume would change to this:

    void Consume()
    {
        while (true) // Keep consuming until
        { // told otherwise.
            string item;
            lock (locker)
            {
                while (_itemQ.Count == 0) Monitor.Wait(locker);
                item = _itemQ.Peek();
                if (item != null) _itemQ.Dequeue();
                else Monitor.PulseAll(); // if the head of the queue is null then make sure all other threads are also woken up so they can quit
            }
            if (item == null)  // This signals our exit.
            {
                if (Interlocked.Decrement(ref _ActiveThreads) == 0)
                {
                    OnCompleted(EventArgs.Empty);
                }
                return;
            }
    
            DoSomething(item); // Execute item.
            OnItemProcessed();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm working on an asp.net application which uses Lucene.net I need to highlight the
I am working with asp.net website project that some of pages need authentication. I
I am working on a .NET project, which needs to interact with some user
I am working on a project in VB.Net and need to implement the DAL.
I am working on a project in asp.net c#. I need to implement horizontal
I'm working with a intranet website written in ASP.NET and need to be able
I'm working in a .net application where we need to generate XML files on
I'm working with C#.net developing applications for windows mobile 6, and i need get
I am working on an old ASP web app (not .net) and I need
I need to begin working with milliseconds in .Net 3.0. The data will be

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.