Geeks With Blogs

News
Welcome to my blog.
Here's what we've got on the menu today:

Lorin Thwaits A geek says what?

With careful programming, threads offer a great way to make your application more responsive.  If you need to do some database access or call a web service, many millions of computer cycles could go unused before your application actually gets underway again.  Instead of making your application sit on the bench that whole time, you may be able to keep it busy with other important tasks.  This post offers a simple introduction to spawning your first thread.

Here's a couple of lines that will kick off a method called "myMethod()" in its own new thread:

System.Threading.Thread myThread=new System.Threading.Thread(
   new System.Threading.ThreadStart(myMethod));
myThread.Start();

The new thread runs in the same memory as the rest of the assembly, so it can access all the same properties and methods of the application.  Its priority can be set lower (using myThread.Priority) so it can complete in the background while other UI-centric events are being handled.  This way the application still feels very responsive to the user.

When throwing new threads, it's important to make sure you don't run into strange concurrency issues.  Think of it being the difference between living alone and living with someone.  Nobody is around to squeeze the toothpaste tube in the middle when you're living alone, and similiarly those single-threaded apps won't get surprised by anything else messing with the state of what's stored in memory.  So make sure when you have multiple threads active that they won't compete with each other causing a “deadlock“ type situation.  Peter Bosch's article about threading gives more details and talks about using monitors to avoid such trouble.

Incidentally, when writing computationally intensive WinForms apps for newer multi-core processors these kinds of multi-threaded applications are usually the only way to get the entire performance available from the processor.  More thoughts about multithreading for performance can be found in my earlier post “Keeping Moore's Law Alive: This time the ball is in our court”.

Posted on Monday, July 17, 2006 10:50 AM ASP.NET , WinForms , Performance | Back to top


Comments on this post: Multi-threaded applications are a cinch in .NET

# re: Multi-threaded applications are a cinch in .NET
Requesting Gravatar...
Lorin,

Just bored and going through my friends archives. :)

Check this "little" ebook about threading in .NET.
http://www.albahari.com/threading/

Cheers,
Chris
Left by Chris Martin on Sep 08, 2006 7:39 PM

Your comment:
 (will show your gravatar)


Copyright © Lorin Thwaits | Powered by: GeeksWithBlogs.net