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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T06:19:06+00:00 2026-06-04T06:19:06+00:00

I am trying to setup multiple BackgroundWorker s to do work and when not

  • 0

I am trying to setup multiple BackgroundWorkers to do work and when not busy start doing the next bit of work. I can’t seem to get them working properly. I have the below code.

When I set FilesToProcess equal or less than MaxThreads it works perfectly although if I make it higher, the app freezes.

I am sure it is something simple, but I just can’t see it.

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace bgwtest
{
    public partial class Form1 : Form
    {
        private const int MaxThreads = 20;
        private const int FilesToProcess = 21;
        private BackgroundWorker[] threadArray = new BackgroundWorker[MaxThreads];

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1Load(object sender, EventArgs e)
        {
            InitializeBackgoundWorkers();
        }

        private void InitializeBackgoundWorkers()
        {
            for (var f = 0; f < MaxThreads; f++)
            {
                threadArray[f] = new BackgroundWorker();
                threadArray[f].DoWork += new DoWorkEventHandler(BackgroundWorkerFilesDoWork);
                threadArray[f].RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorkerFilesRunWorkerCompleted);
                threadArray[f].WorkerReportsProgress = true;
                threadArray[f].WorkerSupportsCancellation = true;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (var f = 0; f < FilesToProcess; f++)
            {
                var fileProcessed = false;
                while (!fileProcessed)
                {
                    for (var threadNum = 0; threadNum < MaxThreads; threadNum++)
                    {
                        if (!threadArray[threadNum].IsBusy)
                        {
                            Console.WriteLine("Starting Thread: {0}", threadNum);

                            threadArray[threadNum].RunWorkerAsync(f);
                            fileProcessed = true;
                            break;
                        }
                    }
                    if (!fileProcessed)
                    {
                        Thread.Sleep(50);
                    }
                }
            }
        }

        private void BackgroundWorkerFilesDoWork(object sender, DoWorkEventArgs e)
        {
            ProcessFile((int)e.Argument);

            e.Result = (int)e.Argument;
        }

        private static void ProcessFile(int file)
        {
            Console.WriteLine("Processing File: {0}", file);
        }

        private void BackgroundWorkerFilesRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }

            Console.WriteLine("Processed File: {0}", (int)e.Result);
        }
    }
}
  • 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-04T06:19:08+00:00Added an answer on June 4, 2026 at 6:19 am

    The problem appears to be that your workers are never completing. Why this is, I’m not sure; it has something to do with the fact that the method (and thread) you are running them from is not itself completing. I was able to solve the problem by creating another worker to assign files to the worker array:

        private BackgroundWorker assignmentWorker;
    
        private void InitializeBackgoundWorkers() {
            assignmentWorker = new BackgroundWorker();
            assignmentWorker.DoWork += AssignmentWorkerOnDoWork;
            // ...
        }
    
        private void AssignmentWorkerOnDoWork( object sender, DoWorkEventArgs doWorkEventArgs ) {
            for( var f = 0; f < FilesToProcess; f++ ) {
                var fileProcessed = false;
                while( !fileProcessed ) {
                    for( var threadNum = 0; threadNum < MaxThreads; threadNum++ ) {
                        if( !threadArray[threadNum].IsBusy ) {
                            Console.WriteLine( "Starting Thread: {0}", threadNum );
    
                            threadArray[threadNum].RunWorkerAsync( f );
                            fileProcessed = true;
                            break;
                        }
                    }
                    if( !fileProcessed ) {
                        Thread.Sleep( 50 );
                        break;
                    }
                }
            }
        }
    
        private void button1_Click( object sender, EventArgs e ) {
            assignmentWorker.RunWorkerAsync();
        }
    

    I’m not happy with this answer because I don’t know why, exactly, it didn’t work as you originally designed it. Perhaps someone else can answer that…? At least this will get you a working version.

    EDIT: Your original version didn’t work because the BackgroundWorkerFilesRunWorkerCompleted runs on the same thread as button1_Click (the UI thread). Since you are not freeing up the UI thread, the thread is never getting marked as complete.

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

Sidebar

Related Questions

I am trying to setup drupal to host multiple sites which will not effect
I am trying to get the following setup right: A given application (with multiple
Trying to setup and get going with the RestKit library for a cocoa project
I am trying to get the following setup up going. Flatpages: Where all my
I'm trying to setup a structure where I can have some shared code base
I'm trying to work out the best way to setup our multi-module Apache Maven
I'm trying to create a work schedule creator with multiple stores and each store
I am trying to setup a ajax progress bar for my site. Sometimes multiple
I'm trying to setup multiple school in a single moodle installation I know Moodle
I'm using Django and Celery and I'm trying to setup routing to multiple queues.

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.