Running Worker Thread in C#
.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() { InitializeComponent(); // 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 m_EventStopThread.Reset(); m_EventThreadStopped.Reset(); // create worker thread instance m_WorkerThread = new Thread(new ThreadStart(this.WorkerThreadFunction)); m_WorkerThread.Name = "Worker Thread Sample"; // looks nice // in Output window m_WorkerThread.Start(); } // Worker thread function. // Called indirectly from btnStartThread_Click private void WorkerThreadFunction() { LongProcess longProcess; longProcess = new LongProcess(m_EventStopThread, m_EventThreadStopped, this); longProcess.Run(); } // 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" m_EventStopThread.Set(); // 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}), 100, true) ) { break; } Application.DoEvents(); } } } // Add string to list box. // Called from worker thread using delegate and Control.Invoke private void AddString(String s) { listBox1.Items.Add(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"; Thread.Sleep(400); // 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 m_EventStopped.Set(); return; } } // Make asynchronous call to main form // to inform it that thread finished m_form.Invoke(m_form.m_DelegateThreadFinished, null); } } }

Comments
Goal
Posted by snareenactina on 12/22/2012 04:50pmadministrate 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.
ReplyInteresting
Posted by snareenactina on 11/12/2012 06:03pmmoderators 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 CarRentals.com. 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. www.economycarrental.com is a search engine dedicated to finding you the best economy car rentals quickly, so that you can save money and time. With www.economycarrental.com, 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, www.economycarrental.com will help you look up good rates quickly. hamates Your question has been successfully submitted to Ask.cars.com. 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. Ask.cars.com 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?
Reply