Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

My Friends

My Links

Permanent Posts

Portuguese Communities

Multi-threading in .NET

In .NET 2.0+, if you want to have something run on another thread, you have a number of choices:

  • The classical System.Threading.Thread class
  • The not-so-known System.Threading.ThreadPool
  • The System.ComponentModel.BackgroundWorker
  • Delegates invoked asynchronously

Let's see how we would do it in each case, and what would be the benefits. Let's suppose our thread method looks like this:

private void ThreadMethod(Object state)

{

}

Using System.Threading.Thread

You start a new System.Threading.Thread instance and pass it a pointer to the thread method wrapped in a System.Threading.ParameterizedThreadStart (for an optional state parameter) or System.Threading.ThreadStart delegate, then, you start it, by calling Start:

Thread thread = new Thread(state => ThreadMethod(state));

thread.Start(state); 

As you can see, I am using the new .NET 3.5 lambda syntax for delegates.

If you want to wait for the thread to exit, do this:

thread.Join(timeout);

 

Using System.Threading.ThreadPool

Assuming your thread pool is properly configured (maximum number of threads, minimum number of threads before creating another one, etc), all you have to do is enqueue a method for execution, whenever a thread from the pool is free:

Boolean result = ThreadPool.QueueUserWorkItem(ThreadMethod, state);

Or, if you must wait for the result:

ManualResetEvent handle = new ManualResetEvent(false);

ThreadPool.RegisterWaitForSingleObject(handle, (s, timedout) => ThreadMethod(s), state, timeout, true);

handle.WaitOne();

By the way, QueueUserWorkItem always returns true, otherwise an exception is thrown.

 

Using System.ComponentModel.BackgroundWorker

You create an instance of the System.ComponentModel.BackgroundWorker class, add an event handler to its DoWork event, and start the processing by calling RunWorkerAsync, with an optional state parameter:

BackgroundWorker worker = new BackgroundWorker();worker.DoWork += delegate(Object sender, DoWorkEventArgs args) { ThreadMethod(args.Argument); };

worker.RunWorkerAsync(state); 

Waiting for the worker to complete is accomplished this way:

ManualResetEvent handle = new ManualResetEvent(false);

ThreadPool.RegisterWaitForSingleObject(handle, (s, timedout) => ThreadMethod(s), state, timeout, true);

handle.WaitOne();

The System.ComponentModel.BackgroundWorker class is available from the Windows Forms toolbox, in design view, so you can drag it into your form, and change its properties or register events through the property inspector.

 

Using Delegates

You declare a delegate that points to your method and you start its BeginInvoke method, passing it the state parameter and optionally a callback method, that gets called when the method terminates, and a state argument for that callback: Action<Object> action = ThreadMethod;

action.BeginInvoke(state, null, null);

And waiting:

Action<Object> action = ThreadMethod;IAsyncResult result = action.BeginInvoke(state, null, null);

result.AsyncWaitHandle.WaitOne(timeout);

 

So, what is the difference between all these methods? Let's see:

  • You would use System.Threading.Thread class when you want your task to be run exactly now; you may also want to suspend it or kill it;
  • System.Threading.ThreadPool helps preserving resources: no new threads are created, we just grab another one from the pool, if it is available, or wait for it, so the job may not start immediately; you don't have control over the actual thread that does the job;
  • If you want to have feedback from a thread, you use System.ComponentModel.BackgroundWorker. Its events allows you to set the completion status and to be notified when the task finishes. Typically you use it in a Windows Forms application. As it uses internally the thread pool, jobs may not start immediately;
  • Delegates are a fast way of launching a thread from a method delegate; it also uses the thread pool, so a task may take some time to actually start.

In all cases, starting from .NET 2.0, the spawned threads retain the same principal (System.Threading.Thread.CurrentPrincipal property), which is great for access control.

Bookmark and Share

Comments

Thread Synchronization in .NET | I love .NET! said:

Pingback from  Thread Synchronization in .NET | I love .NET!

# September 10, 2009 10:46 AM

9eFish said:

9efish.感谢你的文章 - Trackback from 9eFish

# September 10, 2009 11:27 AM

Twitter Trackbacks for Multi-threading in .NET - Development With A Dot [asp.net] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 Multi-threading in .NET - Development With A Dot         [asp.net]        on Topsy.com

# September 10, 2009 11:53 PM

mihailik said:

Such a glorious misuse of lambdas!

-----------

Thread thread = new Thread(state => ThreadMethod(state));

thread.Start(state);

As you can see, I am using the new .NET 3.5 lambda syntax for delegates.

# September 18, 2009 10:36 AM

tamearguero said:

Madonna - Superpop (2009)

<IMG>i34.tinypic.com/.../IMG>

01.Superpop

02.Triggering (Your Senses)

03.Me Against The Music

04.Hey You

05.Cyber-raga

06.Be careful (Cuidado Con Mi Corazon)

07.Keep The Trance

08.Fighting Spirit

09.Lo Que Siente La Mujer

10.Liquid Love

11.Is This Love (Bon d’accord)

12.Wonderland

13.Ring My Bell

14.Your Honesty

15.History

16.Get Stupid

17.Like An Angel Passing

copy this link

<code> www.uploading.com/files/4f5f2a8a/Madonna-Superpop.rar </code>

# September 29, 2009 12:06 PM

Ronaacaro said:

Welcome to MYBETWINN, the investment fund specializing in betting on sports events through bookmakers.

All investments are managed by a skilled team of professionals in the field, providing a steady income to all participants.

MYBETWINN provides a modern and simple way to earn money on the internet.

Types of investments:

Plan A: 20$ to $499 - 29 days investment period paying 1.5% daily

Plan B: $500 and upwards + 10% - 39 days investment period paying 2.5% daily

http://mybetwinn.net?ref=399 - For more details, please register at MyBetWinn.net

# October 4, 2009 10:10 AM

NickyVv said:

Hi

This is my first post on this forum, so it better be a good one! :) I hope this hosting coupon code will be useful to some people..

It's for ThinkHost and gives you $30 off for all plans (except custom ones)

Here's the coupon code: <b>oak_thinkhostV5</b>

Hope I helped!

<img>www.pppcm.com/.../img>

# October 13, 2009 6:25 PM

exceedimmew said:

Hey Everyone just intorducing myself here. Nice forum and glad i got the chance to join and hope to become an active member soon!

# November 14, 2009 2:59 AM

Nutedubre said:

Hey there everyone i was just introduceing myself here im  a first time visitor who hopes to become a daily reader!

# November 15, 2009 10:39 AM

Nutedubre said:

Why hello associate forum people! I well-grounded wanted to introduce myself here as this looks like a dialect right attractive forum! I myself am gripping in things like writeing and computer fixing up so if anyoune needs steal forgive me differentiate! I also Suffer from Sciatica so if you aslo secure this condition suffer to me know so we can stake some stretches!

# November 17, 2009 12:39 PM

AabidaJamshut said:

Hello all

I'm sorry - i'm inexperienced with computer. Im from Sirya!

I need help about Anti-aging and HGH!

I know that HGH injection is very good for antiaging, but I dont have much money for it...

Is there any good and effective HGH or Anti-Aging supplement that works good and is not too expensive?

I need to look young and beautiful for my Husband, please!

# November 27, 2009 10:02 PM

ChungLeeGirl said:

Hi all

Christmas holidays are coming soon!

please help me :

What would be the good gift for guy for these holidays?

I'm totally out of any ideas,tired thinking and i need help!

Im 19F, he is 20

Thanks all

for your

help  and advice!

# December 3, 2009 8:50 PM

MohammadSah said:

hi

excuse me im new to internet and also

very embarassed to ask about this...

Anyone tried MaxVIGRA anti-ED supplement for men?

I was adviced that MaxVIGRA works better and is cheaper than Vagra and such...

Is that true? Please help me... i m shy to go to a doctor

# December 15, 2009 6:50 AM

Foeperronense said:

whatsup this forum rocks!

just registered and wanted to say hello

i am  22 years old and from the uk and i am studying fashion

# December 18, 2009 9:48 AM

Krista30Us said:

It’s not really easy to learn information about this topic,but essays writers will propose to <a href=" http://www.essayslab.com">buy an essay</a> to have true information and it’s doable to purchase already written essay per really good costs!

# January 28, 2010 4:19 AM

Herryavessamn said:

Does enybody know? Need help finding the right one..

I never go to escort girls for meeting, but i was sow same escorts sites and i was really like one girl     escortplius.com/.../Sindy--Escort-from-France.html

Maybe someone know about her? i am asking because it will be my first meeting and i dont know if its good choice for the first meet. I hope to get same info about this girl

# February 12, 2010 8:10 PM

arrefebem said:

<a href=www.anobii.com/mobilscanertela>%D1%81%D0%BA%D0%B0%D1%87%D0%B0%D1%82%D1%8C мобильный сканер одежды</a>

софт сканер на телефон

# February 20, 2010 1:56 PM

wachenceBeile said:

The newly presented iPad of Apple is awesome, terrific and incredible computer system. It is super high quality, super responsive and super processor. This technology is most advanced version ever developed.

Apple iPad has superior surfing speed as you can quickly flick through multiple pages tapping each on a block. And unlike the iPhone you now have complete webpages without much effort.

Click Here to Grab <a href="www.ipadqa.com/.../">Apple iPad at Cheap Price</a>

# February 23, 2010 9:59 AM

MelissaSinclair said:

Hi,Hello everyone,

I've got a question both to men and women -

Anyone tried Goat weed or "Horny" goat weed ?

Does it actually work and is it an effective libido enhancer both for women and men?

Thanks in advance for your replies

# March 18, 2010 8:52 PM

LearnSEOTL said:

Hey everyone, first post!

What is your top five tips for better SEO on your website?

Mine are:

Accurate Title Tags

Backlinks

Keyword Rich Content

Link Structure

Relevancy

# April 25, 2010 7:01 PM

JinLeeHui said:

Hi,

sorry, Im new to forums.  My job is to complete survey about organic chinese green teas.

If you have a minute, then could you please message me which is your favorite brand of green tea?

Thanks in advance,

Yours Jin

# April 28, 2010 2:22 PM

OnlineDirect ~ said:

Network of online directories in different categories. http://usseeker.com

# May 18, 2010 5:40 PM

musiccontrac a said:

Get instant access to over 100 of the music industry most used Music Contracts.http://www.Order-Yours-Now.com

# May 21, 2010 2:11 PM

ecofriendly said:

we rent eco-friendly, reusable plastic moving boxes. Our goal is to help people move smart, and we do this by offering an affordable alternative to traditional cardboard moving boxes.<a href=http://www.ecopackrental.com>eco-friendly</a>

# May 25, 2010 9:09 AM

ChrissyBe said:

Sorry if this is off topic.

Does anyone know http://www.escortmatcher.com - www.escortmatcher.com?

There seems an unreal amount of local escorts in my area?

Thanks

ChrissyBe

# May 27, 2010 2:34 AM

AnitotrartMaw said:

I enjoyed reading your blog. Keep it that way.

# August 21, 2010 6:41 PM