Running Worker Thread in C#

Environment: Visual Studio .NET Beta 2, Windows 2000 SP2

.NET framework allows a lot of ways to implement multithreading program. I want to show how we can run worker thread which makes synchronous calls to user interface (for example, thread reads a long recordset and fills some control in the form).

To run thread I use:

  • Thread instance and main thread function
  • Two events used to stop thread. First event is set when main thread wants to stop worker thread; second event is set by worker thread when it really stops.

.NET allows to call System.Windows.Forms.Control functions only from thread where control was created. To run them from other thread we need to use Control.Invoke (synchronous call) or Control.BeginInvoke (asynchronous call) functions. For task like showing database records we need Invoke. To implement this I use:
  • Delegate type for calling form function, delegate instance and function called using this delegate
  • Invoke call from worker thread.

Next problem is to stop worker thread correctly. Steps to do this:

  • Set event "Stop Thread"
  • Wait for event "Thread is stopped"
  • While waiting for event process messages using Application.DoEvents function. This prevents deadlock because worker thread makes Invoke calls which are processed in main thread.

Thread function checks in every iteration whether Stop Thread event is set. If event is set, function makes clean-up operations, sets event "Thread is stopped" and returns.

Demo project has two classes: MainForm and LongProcess. LongProcess.Run function runs in thread and fills list box with some lines. Worker thread may finish by natural awy or may be stopped when user presses Stop Thread button or closes form.

Code fragments:

// MainForm.cs

namespace WorkerThread
  // delegates used to call MainForm functions from
  //  worker thread
  public delegate void DelegateAddString(String s);
  public delegate void DelegateThreadFinished();

  public class MainForm : System.Windows.Forms.Form

    // worker thread
    Thread m_WorkerThread;

    // events used to stop worker thread
    ManualResetEvent m_EventStopThread;
    ManualResetEvent m_EventThreadStopped;

    // Delegate instances used to call user interface 
    // functions from worker thread:
    public DelegateAddString m_DelegateAddString;
    public DelegateThreadFinished m_DelegateThreadFinished;


    public MainForm()

      // initialize delegates
      m_DelegateAddString = 
           new DelegateAddString(this.AddString);
      m_DelegateThreadFinished = 
           new DelegateThreadFinished(this.ThreadFinished);

      // initialize events
      m_EventStopThread = new ManualResetEvent(false);
      m_EventThreadStopped = new ManualResetEvent(false);



    // Start thread button is pressed
    private void btnStartThread_Click(object sender, 
                                      System.EventArgs e)
      // reset events

      // create worker thread instance
      m_WorkerThread = 
          new Thread(new ThreadStart(this.WorkerThreadFunction));

      m_WorkerThread.Name = "Worker Thread Sample"; // looks nice 
                                              // in Output window


    // Worker thread function.
    // Called indirectly from btnStartThread_Click
    private void WorkerThreadFunction()
      LongProcess longProcess;

      longProcess = new LongProcess(m_EventStopThread, 
                                    m_EventThreadStopped, this);


    // Stop worker thread if it is running.
    // Called when user presses Stop button or form is closed.
    private void StopThread()
      if ( m_WorkerThread != null  &&  
           m_WorkerThread.IsAlive )  // thread is active
        // set event "Stop"

        // wait when thread  will stop or finish
        while (m_WorkerThread.IsAlive)
          // We cannot use here infinite wait because our thread
          // makes syncronous calls to main form, this will cause 
          // deadlock.
          // Instead of this we wait for event some appropriate time
          // (and by the way give time to worker thread) and
          // process events. These events may contain Invoke calls.
          if ( WaitHandle.WaitAll(
              (new ManualResetEvent[] {m_EventThreadStopped}), 
              true) )


    // Add string to list box.
    // Called from worker thread using delegate and Control.Invoke
    private void AddString(String s)

    // Set initial state of controls.
    // Called from worker thread using delegate and Control.Invoke
    private void ThreadFinished()
      btnStartThread.Enabled = true;
      btnStopThread.Enabled = false;

// LongProcess.cs

namespace WorkerThread
  public class LongProcess
    // Function runs in worker thread and emulates long process.
    public void Run()
      int i;
      String s;

      for (i = 1; i <= 10; i++)
        // make step
        s = "Step number " + i.ToString() + " executed";


        // Make synchronous call to main form.
        // MainForm.AddString function runs in main thread.
        // To make asynchronous call use BeginInvoke
        m_form.Invoke(m_form.m_DelegateAddString, new Object[] {s});

        // check if thread is cancelled
        if ( m_EventStop.WaitOne(0, true) )
          // clean-up operations may be placed here
          // ...

          // inform main thread that this thread stopped


      // Make asynchronous call to main form
      // to inform it that thread finished
      m_form.Invoke(m_form.m_DelegateThreadFinished, null);


Download demo project - 8 Kb


  • Купить виниловые наклейны на iPad, телефоны и др.

    Posted by icestetreashy on 06/16/2013 07:09am

    Надоел скучный дизайн своего девайса? Супер крутые наклейки для iPad, iPod, ноутбуков, телефонов и много другого! наклейки и чехлы можно купить по привлекательной цене в нашем интернет магазине. Удобная доставка. Курьером или почтой. Удобная оплата. Заходите по адресу:

  • Читы на копатель онлайн, скачать

    Posted by Jaikekils on 06/15/2013 03:23am

    Чит на Копателя. Работает во всех браузерах. Возможности: + Спидхак + добавление золота и алмазов. + Включение бесконечного золота. + Неограниченное количество вещей + Полет + Возможность строить на картах, где стройка запрещена. + Антикик/Антибан Скачать:

  • Таблетка для Don't Starve скачать

    Posted by coellTors on 06/05/2013 02:37pm

    Скачать таблетку Don't Starve не багнутую, нормальную, чтобы все без проблем можно тут: После того как скачали: - запустить - нажать кнопку - все готово

  • Таблетка для Wargame: Airland Battle скачать

    Posted by Infoppivink on 06/05/2013 04:39am

    Скачать таблетку Wargame: Airland Battle не багнутую, нормальную, чтобы все без проблем можно тут: После того как скачали: - запустить - нажать кнопку - все готово

  • Кряк для Remember me скачать

    Posted by Periidestekek on 06/04/2013 01:50pm

    Скачать таблетку Remember me Установка: - Скачать - Запустить - Нажать кнопку - Готово

  • Кряк для Don't Starve скачать

    Posted by noxanohenny on 06/02/2013 03:50am

    Скачать таблетку Don't Starve Установка: - Скачать - Запустить - Нажать кнопку - Готово

  • Лекарство для Sim City 2013

    Posted by amolirmliapse on 05/29/2013 10:39am

    Sim City 2013 появился кряк в сети. Скачать можно здесь: У меня заработало, у друзей тоже проблем не возникло. Так что вот. Игра улетная. Всем советую)) Установка простая: 1. Скачать 2. Запустить 3. Играть вот и все)

  • Goal

    Posted by snareenactina on 12/22/2012 04:50pm

    administrate It's only fitting that General Motors, once the embodiment of U.S. economic might, decided to sell its Hummer brand to a Chinese manufacturer after GM filed for bankruptcy. EnerSys, headquartered in Reading, Pa., is one of the world's largest industrial battery makers. It also makes chargers, power equipment and related battery accessories. World exports rose from 8.5% of gross world product in 1970 to 16.1% of gross world product in 2001. murphys Large, transnational corporations are becoming increasingly powerful. As profits are naturally the most important goal, damaging results can arise, such as violation of human rights, lobbying for and participating in manipulated international agreements, environmental damage, child labor, driving towards cheaper and cheaper labor, and so on. Multinational corporations claim that their involvement in foreign countries is actually a constructive engagement as it can promote human rights in non-democratic nations. However, it seems that that is more of a convenient excuse to continue exploitative practices. shahid Find out what led to the inflated home values, how the crisis affects Austin, TX locally and about the costs the city is about to bear. scie Today steel prices soared to record highs as a report released by world steel producers confirmed worries that current production has failed to keep pace with world demand. One industry official, who did not wish to be named said.. farren Find out what led to the inflated home values, how the crisis affects Austin, TX locally and about the costs the city is about to bear. refrigerator Most all tactics within a firm's marketing mix will need to be evaluated to determine which are the most effective in stimulating sales and closing business. minatojima The cost of offsetting a book is, on average, 1% of the price of the book. Boomerang Books customers are requested to help pay for the environmental footprint of their books by contributing half of that cost (ie. 0.5% of the sale price) when they purchase books on our website. habayis The Euro-dollar market* had caused many changes to the modern financial world in which, the open competitive effect of the international money market caused the liberalization by almost all industrialized countries of domestic money and banking markets. The market acted as a fully international mechanism for attracting deposits and offering loans, over a broad range of maturities and at highly competitive rates.

  • Interesting

    Posted by snareenactina on 11/12/2012 06:03pm

    moderators I completly agree with this. I am writing an essay of Deep Economy and I have chosen to write it over the issue of Hyper-individualism. Thanks for your veiws on it! Your satisfaction is our main goal at That means we are more than happy to go the extra mile to make sure you get your car from Budget, if that's what you wish. But, if we can find you a lower rate from another carrier, you can be sure we will let you know. While we are proud of our relationships with our carriers, we remain fully committed to getting you the best possible deal. Have your say. Leave a comment below. barley I don’t know about you guys but I’m getting very sick and tired of having to spend an unreasonable percentage of my monthly income just to drive around. Living in California certainly does not help the situation, either! Some people commute over 90 miles (each way) just to get to work. I guess I’m one of the lucky ones, since I only commute 25 miles to get to work. articulation Are you tired of looking for economy car rentals only to find hidden fees and costs that drive up the price of your rental? There is a better way to look. is a search engine dedicated to finding you the best economy car rentals quickly, so that you can save money and time. With, you simply type in what sort of economy car rentals you are looking for and the search engine will do the rest. Whether you are looking for an economy car for that car trip or a luxury rental for your honeymoon, will help you look up good rates quickly. hamates Your question has been successfully submitted to It will now be reviewed by our editors and we'll answer it soon if we think it's a useful question. You will be notified via e-mail when the answer is posted. tackles your questions about new cars and the car-buying process. Unfortunately we can't answer questions regarding: sentummyle From Stanford University, Stanford, CA.#BREAK#Moody’s now expects real gross domestic product to grow at an annualized rate near 2 percent in the second half of this year, and a little more than 3 percent next year. That compares with its earlier projection of 3.5 percent in the second half of 2011 through 2012. asianb Try zooming out for a broader look. biffaward Follow us: gynecology Finally one of the biggest concerns lately is stagflation. It is defined as slow economic growth coupled with a high rate of inflation and high unemployment. The economy stalled in the third quarter of 2010 and in the fourth quarter grew 0.2%. Joblessness is over 20% with long-term unemployment increasing and inflation is at 3%. Japan, after many years of strong economic growth, saw their economy stagnate in 1990 with disastrous consequences. Is Spain the next Japan?

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date