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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T05:34:44+00:00 2026-06-01T05:34:44+00:00

Problem How can I do work in one thread and update a progressbar on

  • 0

Problem

How can I do work in one thread and update a progressbar on the main thread?

Summary

Below is my attempt to solve the problem, but it’s not working. I believe the reason is that the updates are getting queued in the Windows message pump, but then all executed at once so they happen so fast the user doesn’t see them.

Details

I’m trying to create a GUI app that will do work with threads in the background and update a progressbar. I realize that I would have a simpler time using a backgroundworkerprocess but that is taking away some flexibility I need.

I’m using InvokeRequired and callback functions to handle calls from the worker thread to the main thread so thread safety shouldn’t be an issue.

On my PC when I click button1 it takes the worker thread about 5 seconds to finish its work and output the results to textbox1. During that time the worker thread makes about 100 calls to the updateProgressBar function. This function is executing:

progressBar1.Value = percent;
progressBar1.Update();
progressBar1.Refresh();
progressBar1.Invalidate();

However, the effects of these commands are never seen by the user. I believe they are all getting put into the message pump to update the GUI, but that they are just getting queued up and all executed at once.

I’ve tried inserting sleeps and playing around with the flow of the work being done but that hasn’t helped. How can I get the progressbar updates flushed?

Just to note, this is a contrived example to illustrate the problem.

Code

// Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Text.RegularExpressions;

namespace ProgressBarExample
{
    public partial class Form1 : Form
    {
        Thread processThread;
        delegate void updateGUICallback(int read, int unread);
        delegate void updateProgressBarCallback(int percent);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string input = "abc1234 123456 domain\abc1234 123 0\r\n";

            // Create 1048576 lines of input
            for (int i = 0; i < 20; i++)
                input += input;

            processThread = new Thread(new ParameterizedThreadStart(processData));
            processThread.Start(input);
        }

        private void processData(object input)
        {
            // Break the input on newlines
            string[] lines = Regex.Split((string)input, "\r\n");

            int readLines = 0;
            int unreadLines = 0;
            int maxLines = lines.Length;


            // Setup for regex
            Match match;
            string pattern = @"^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)$";

            // Read each line of input
            for (int i = 0; i < maxLines; i++)
            {
                // Attempt a regex match
                match = Regex.Match(lines[i].Trim(), pattern);

                // If the line matches our expected entry, add it to the list
                if (match.Success)
                {
                    readLines++;
                }
                else
                {
                    unreadLines++;
                }

                // Update the progressbar every 10000 iterations
                if (i % 10000 == 0)
                {
                    updateProgressBar(i / maxLines);
                }
            }

            updateTextbox(readLines, unreadLines);
        }

        private void updateTextbox(int read, int unread)
        {
            if (textBox1.InvokeRequired)
            {
                updateGUICallback cb = new updateGUICallback(updateTextbox);
                this.Invoke(cb, new object[] { read, unread });
            }
            else
            {
                textBox1.Text = "Read: " + read + "\r\n" +
                    "Unread: " + unread;
            }
        }

        private void updateProgressBar(int percent)
        {
            if (progressBar1.InvokeRequired)
            {
                updateProgressBarCallback cb = new updateProgressBarCallback(updateProgressBar);
                this.Invoke(cb, new object[] { percent });
            }
            else
            {
                progressBar1.Value = percent;
                progressBar1.Update();
                progressBar1.Refresh();
                progressBar1.Invalidate();
            }
        }

    }
}
  • 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-01T05:34:45+00:00Added an answer on June 1, 2026 at 5:34 am

    This may be a coincidence in your contrived example, but the line

    updateProgressBar(i / maxLines);
    

    should really read as

    updateProgressBar(100 * i / maxLines);
    

    when you use the Windows Forms designer’s defaults. I have just checked it with the modification and the progress bar updates regularly, just as you (probably) want it to.

    With that said, having to prepend every method body with the Invoke() or BeginInvoke() drudgery is really going to be awkward and unless the flexibility you mentioned is paramount, I would not dismiss the BackgroundWorker approach so easily.

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

Sidebar

Related Questions

I have a classic physics-thread vs. graphics-thread problem: Say I'm running one thread for
can some one explain why I face problem with backgroundworker backgroundWorker1_RunWorkerCompleted works just fine
I read one article, describing the ABA problem, but there is something, that I
I've got some threads doing heavy work while my main thread handles the UI
EDIT: Update - scroll down EDIT 2: Update - problem solved Some background information:
I have a problem using DatagramSocket. The problem is that I can't run two
Straight to the Qeustion ->. The problem : To do async bulk inserts (not
I've an application where user can schedule custom timer jobs which runs only one
This question looks like this one : Programmatically binding List to ListBox but as
I have a problem in understanding how the winapi condition variables work. On the

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.