Calling Your Main Thread From A Worker Thread In C#

CK CK 3788 
Created at  
545 0 0
There are many cases where it is necessary to let your main application
know that a thread has completed. Your main application could spawn
some threads to do background work and then when the threads have
completed their work they could return the results back to the main
application. This would be beneficial since it would leave the main
thread free and ready to respond to the user. We will create a new
application that will spawn two thread that will each modify a label on
a form, when the classes are finished executing they will call back to
the main thread to let it know that they have completed execution.

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

namespace WindowsApplication1
{       
   public class Counter
   {       
      private Label LabeltoUpdate;
      private int MaxCount;
      private CallBack CallBackMethod;
       
      public Counter(Label l,int max, CallBack cb)
      {
          LabeltoUpdate = l;
          MaxCount = max;
          CallBackMethod = cb;
      }

      public void BeginProcessing()
      {
          int i;

          for(i=1;i < MaxCount; i  )
          {
             LabeltoUpdate.Text = i.ToString();
             LabeltoUpdate.Refresh();
          }

          //Tell the main thread we have completed
          CallBackMethod(i,Thread.CurrentThread.Name);
      }
   }
}

using System.Threading;

private void button1_Click(object sender, System.EventArgs e)
{
   Counter c1 = new Counter(label1,3000,new CallBack(ThreadCompleted));
   Counter c2 = new Counter(label2,1500,new CallBack(ThreadCompleted));

   Thread t1 = new Thread(new ThreadStart(c1.BeginProcessing));
   Thread t2 = new Thread(new ThreadStart(c2.BeginProcessing));

   t1.Name = "Counter Thread 1";
   t2.Name = "Counter Thread 2";

   t1.Start();
   t2.Start();
}

private void ThreadCompleted(int intTotal,string strName)
{
   MessageBox.Show("Thread "   strName  
                      " has completed at "   intTotal.ToString());
}

Tags C# CallBack CallBackMethod Thread ThreadStart Facebook X
Comments 0
Similar posts
  1. How to send binary data through C# CGI app?
    993
  2. How To Read And Write A Cookie
    360
  3. Using C# With Cookies
    620
  4. How To Print Text In C#
    453
  5. How to print character in C# by ASCII code
    475
  6. Extracting the Country from IP Address
    466
  7. Graphics in C# - Irregular Forms
    906
  8. How to restrict a program to a single instance
    727
  9. The best way to enable and disable buttons, menu items and toolbar buttons
    667
  10. How to speed up access to the RichTextBox Lines property
    828
  11. To load image from file
    446
  12. How to convert bitmap image to jpeg image ?
    353
  13. How to resize and save PNG or Jpeg Image file ?
    629
  14. How to convert text string to integer ?
    608
  15. How to convert integer to text string ?
    696
  16. How to get process id in C# like windows task manager ?
    867
  17. Thread Application Implementation in TThread
    662
  18. How To Check If Your Printer Is Connected Using C#
    1,025
  19. How to download/grap web pages or XML document at internet website in Delphi XE?
    868
  20. Rust Thread Example
    345
  21. Rust Std library types
    367
  22. Basic Rust Thread Example to Perform Concurrent Computation
    611
  23. The || syntax in Rust - also known as a closure
    599
  24. How do I get the maximum available of thread in python?
    981
  25. Method to maximize full CPU performance with Python
    314
  1. Using the shell to receive notification of removable media being inserted or removed
    680
  2. Adding Custom Paper Sizes To Named Printers
    644
  3. Print HTML In C# With Or Without The Web Browser Control And The Print Dialog
    971
  4. A Customizable Printing Text Class
    427
  5. Simplified .NET Printing In C#
    691
  6. How To Print Text In C#
    453
  7. C# Lists
    1,146
  8. Simple Example of IF/THEN using C#
    1,262
  9. Fast and Good Keyboard/Mouse Test without the message handler
    975
  10. Simple CGI Programming in C
    541
  11. C++ CGI Example working on Apache
    481
  12. Simple C# CGI working on Apache
    476
  13. How to send binary data through C# CGI app?
    993
  14. Interacting With TinyPic From C#
    1,298
  15. Creating A Watched Folder With Assigned Events
    1,652
  16. HashTable Tutorial In C#
    1,785
  17. Stack Tutorial In C#
    665
  18. Queue Tutorial In C#
    1,729
  19. Create PDF Files On the Fly in C#
    990
  20. How to call Visual C/C++ implemented DLL functions in C# - Simple DLLImport
    1,153
  21. Send Email Using C#
    1,376
  22. How To Read And Write A Cookie
    360
  23. Using C# With Cookies
    620
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,728
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    234
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252