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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T00:47:36+00:00 2026-05-25T00:47:36+00:00

I’m calling a couple of functions during a form load and then using the

  • 0

I’m calling a couple of functions during a form load and then using the result to update a label control. if the the functions are long running it stops the form from loading… so I want to make it that the form loads a works while the two functions are called in parallel and when they return it then updates the label here is the calling code both functions return an int.

This a windows Forms app in .Net 4.0

private void mainForm_Load(object sender, EventArgs e)
   {
       currentCount  = func1(tes1);
       allowedCount= func2(test2);
       labelCount.Text = "Using " + func1.ToString() + " of " + func2.ToString();
   }
  • 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-25T00:47:37+00:00Added an answer on May 25, 2026 at 12:47 am

    updated 2001-08-27 to add continuous updates

    I updated the code to also show how to use a .Forms GUI timer component to update a status bar label as background updates occur, also with some various cleanup and additional comments. It’s certainly also possible to do an Invoke() to update your form with information as it comes in, but I think it really doesn’t make much sense to do so. The goal of a UI update is to have adequate visual feedback given to the user, and there’s no need to couple the updating of the fields to the updating of the visual element.

    Also if these updates come in frequently enough, you could end up with a big performance hit from all the calls to Invoke unless you rate-limit them, which is basically what is happening with the timer component anyway.

    I have zipped up the solution and have made it available for download: ParallelButtons-7208779.zip. I’m not entirely certain why I chose that name, but there ya go. 🙂

    So, the code now demonstrates how to do both: what I had originally interpreted the question to mean (to run two threads in parallel in the background, updating a label once both functions of returned), as well as adding in periodic updates of separate counter fields in the background threads that also have a status shown on the GUI, implemented by a Timer component updating the labels in its Tick event.

    For the final update based when the threads end, this setup doesn’t require any synchronization beyond what the structure already provides, at least from the perspective of updating things; I don’t know what your actual functions are doing. (If they interact with one another, they may have some synchronization requirements.) It also very quickly updates the form without even having to worry any sort of coordination or synchronization between the two threads in order to figure out which is responsbile for updating the GUI.

    Form Code

    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.Diagnostics;
    using System.Threading;
    
    namespace ParallelButtons_7208779
    {
        public partial class frmMain : Form
        {
            public frmMain()
            {
                InitializeComponent();
    
                tslblRunStatus.Text = "Updating: please wait...";
                tslblFinalStatus.Text = "";
    
                Thread BackgroundThread =
                    new Thread(() => TwoParallelCalls_UpdateOnlyOnReturn());
    
                BackgroundThread.Start();
    
                // tmrUpdateStatus is a timer component dropped onto the
                // form in design mode. it's initial settings are defaults
                // Interval=100, Enabled=false, and it's Tick event has 
                // been hooked up to tmrUpdateStatus_tick
                tmrUpdateStatus.Start();
            }
    
            // the nice thing about the component timer is that we don't 
            // have to worry about doing an Invoke, we already know that the
            // Tick event is happening on the UI thread.
            private void tmrUpdateStatus_Tick(object sender, EventArgs e)
            {
                // in case a tick fires after both functions complete
                if ((currentCount == -1) || (allowedCount != 1))
                {
                    tslblRunStatus.Text =
                        string.Format(
                            "[running...] Using {0} of {1}",
                            runCurrentCount, runAllowedCount
                        );
                }
                else
                {
                    // We can use this to stop the timer since we are doing the
                    // check in here. If we didn't need to prevent an extra
                    // update after the functions were complete, we could skip
                    // the check in here and stop it elsewhere. (see below)
                    tmrUpdateStatus.Stop();
                }
            }
    
            // The nice thing about having a common method that fires both 
            // functions and then waits for both is that no special thread
            // synchronization is needed.
            //
            // Otherwise there would be a need to use some sort of 
            // sychronization method (e.g. Semaphore, Mutex, lock) to ensure 
            // that the update is handled correctly.
            private void TwoParallelCalls_UpdateOnlyOnReturn()
            {
                // initializing with Lambdas that just set the fields to the
                // result of the function calls.
                Thread thread1 = new Thread(() => currentCount = func1());
                Thread thread2 = new Thread(() => allowedCount = func2());
    
                // start both threads and wait for both to finish
                thread1.Start(); 
                thread2.Start();            
                thread1.Join(); 
                thread2.Join();
    
                // using Invoke to safely update the .Forms GUI component.
                Invoke((Action)
                    (() => 
                    {
                        // this stops the UI update timer from this function, 
                        // we can do this instead of checking status in the
                        // Tick event if we can tolerate extra updates.
                        tmrUpdateStatus.Stop();
    
                        // set the final status test to the label
                        tslblFinalStatus.Text =
                            string.Format(
                                "[final] Used {0} of {1}",
                                currentCount, allowedCount
                            );
                    }
                    ));
            }
    
            #region Background Thread Functionality
    
            // The following functions are just dummy methods to udpate something
            // in the background we can use to watch the results on the UI.
    
            // In this section, I just have two methods that run in the background
            // updating some member fields. 
    
            // fields for intermediate values (set internally while running)
            int runCurrentCount = -1;
            int runAllowedCount = -1;
    
            // fields for a final result (set externally using return value)
            int currentCount = -1;
            int allowedCount = -1;
    
            // holds how long we want the test threads to run
            TimeSpan TestRunTimespan = TimeSpan.FromSeconds(5);
    
            // These methods use the System.Diagnostics.Stopwatch class which
            // has been around since .NET 2.0.
    
            // If you are really wanting to do a task that requires something
            // to happen at particular intervals, you should probably look at
            // an interval timer of some sort. There are several timers
            // available, There are various concerns when choosing one, so 
            // I highly recommend doing research (Stack Overflow has some
            // good answers on this issue if you search on 'Timer'.)
            //
            // Timers: System.Windows.Forms.Timer, System.Threading.Timer,
            // System.Windows.Threading.DispatcherTimer, System.Timers.Timer
    
            private int func1()
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();
    
                while (stopWatch.Elapsed < TestRunTimespan)
                {
                    runCurrentCount += 5;
                    Thread.Sleep(100);
                }
    
                runCurrentCount += 10;
    
                return runCurrentCount;
            }
    
            private int func2()
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();
    
                while (stopWatch.Elapsed < TestRunTimespan)
                {
                    runAllowedCount += 10;
                    Thread.Sleep(100);
                }
    
                runAllowedCount += 10;
    
                return runAllowedCount;
            }
    
            #endregion
    
        }
    }
    

    Form Designer Code

    namespace ParallelButtons_7208779
    {
        partial class frmMain
        {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
    
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
    
            #region Windows Form Designer generated code
    
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                this.components = new System.ComponentModel.Container();
                this.statusStrip1 = new System.Windows.Forms.StatusStrip();
                this.tslblRunStatus = new System.Windows.Forms.ToolStripStatusLabel();
                this.tslblFinalStatus = new System.Windows.Forms.ToolStripStatusLabel();
                this.tmrUpdateStatus = new System.Windows.Forms.Timer(this.components);
                this.statusStrip1.SuspendLayout();
                this.SuspendLayout();
                // 
                // statusStrip1
                // 
                this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                    this.tslblRunStatus,
                    this.tslblFinalStatus});
                this.statusStrip1.Location = new System.Drawing.Point(0, 208);
                this.statusStrip1.Name = "statusStrip1";
                this.statusStrip1.Size = new System.Drawing.Size(431, 22);
                this.statusStrip1.TabIndex = 0;
                this.statusStrip1.Text = "statusStrip1";
                // 
                // tslblRunStatus
                // 
                this.tslblRunStatus.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenInner;
                this.tslblRunStatus.Name = "tslblRunStatus";
                this.tslblRunStatus.Size = new System.Drawing.Size(80, 17);
                this.tslblRunStatus.Text = "Item {0} of {1}";
                // 
                // tslblFinalStatus
                // 
                this.tslblFinalStatus.Name = "tslblFinalStatus";
                this.tslblFinalStatus.Size = new System.Drawing.Size(60, 17);
                this.tslblFinalStatus.Text = "final status";
                // 
                // tmrUpdateStatus
                // 
                this.tmrUpdateStatus.Tick += new System.EventHandler(this.tmrUpdateStatus_Tick);
                // 
                // frmMain
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(431, 230);
                this.Controls.Add(this.statusStrip1);
                this.Name = "frmMain";
                this.Text = "Background Form Updates - Stack Overflow 7208779";
                this.statusStrip1.ResumeLayout(false);
                this.statusStrip1.PerformLayout();
                this.ResumeLayout(false);
                this.PerformLayout();
    
            }
    
            #endregion
    
            private System.Windows.Forms.StatusStrip statusStrip1;
            private System.Windows.Forms.ToolStripStatusLabel tslblRunStatus;
            private System.Windows.Forms.ToolStripStatusLabel tslblFinalStatus;
            private System.Windows.Forms.Timer tmrUpdateStatus;
    
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I have a French site that I want to parse, but am running into
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I am currently running into a problem where an element is coming back from
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
We are using XSLT to translate a RIXML file to XML. Our RIXML contains

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.