Home > SOA Tips > .NET Developer > Multithreading with the .NET Framework
SOA Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 

.NET DEVELOPER

Multithreading with the .NET Framework


Peter G. Aitken
07.06.2004
Rating: -3.17- (out of 5)


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


When your computer appears to be doing multiple things at once, what is really happening is that the CPU's time is being divided up between the various tasks. This multithreading can help programmers create more user friendly applications. This article from InformIT discusses reasons for multithreading and how to do it within the .NET Framework.


When your computer appears to be doing multiple things at once, what is really happening is that the CPU's time is being divided up between the various tasks. Task 1 -- printing, for example -- gets the CPU for some fraction of a second, then task 2, task 3, and so on. Because the computer is very fast and human perceptions are relatively slow it seems as if the tasks are being done simultaneously. This ability to share the CPU among multiple tasks is called multitasking, and it is a feature of the Windows operating system (and most other operating systems too).

How does threading relate to the .NET programmer? A .NET program by default has a single thread, but you can create two or more threads within a single program if you desire. Because these threads are all part of the same program, or process, they all have access to the program's resources (global, static, and instance fields, for example). But because Windows allocates CPU time based on threads, not processes, a multithreaded program will get more than its normal share of CPU time.

The .NET Framework offers two ways to create a new thread in your program. This article explains the simpler of these two methods, the thread pool, which is perfectly adequate for many uses. The .NET runtime maintains a queue of idle threads and assigns them to programs when requested. When the code that the program executes in the thread is complete, the thread is returned to the pool. This is why this method is so simple; the runtime takes care of most of the details for you via the ThreadPool class.

All ThreadPool threads have normal priority, which is what you want when you are using a second thread to improve program responsiveness. The ThreadPool class and all other multithreading-related classes are in the System. Threading namespace.

To create a new thread, call the static ThreadPool.QueueUserWorkItem method. The syntax is as follows:

ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadCode), Done);
  • ThreadCode is the name of the method in your program where the new thread should start and end executing.
  • Done is an AutoResetEvent object that you use to signal the thread pool manager that the program is finished using the thread.

The method specified by the ThreadCode argument must have the proper signature, matching that of the WaitCallback class. Specifically, it must take one argument of type Object and have a void return value. Code in this procedure must also inform the thread pool that it is finished. Here's an example shows a method that meets these two requirements:

static void MyThreadCode(object state)
{
    //Code to be executed by the thread goes here, including
    //calls to other methods as required. Execution must return
    //here when complete.
    //Tell the thread pool that the thread has finished.
    ((AutoResetEvent)state).Set();
}

You would create this thread and start it running as shown here:

AutoResetEvent IsDone = new 
AutoResetEvent(false);
ThreadPool.QueueUserWorkItem (new WaitCallback(MyThreadCode), IsDone);

Seems too simple to be true, right?


Click over to InformIT to read about the possible downsides of multithreading as well as to view a demonstration of the above method.


Rate this Tip
To rate tips, you must be a member of SearchSOA.com.
Register now to start rating these tips. Log in if you are already a member.


Submit a Tip




Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   



RELATED CONTENT
.NET Developer
Programming Indigo
DataSets and Web services don't mix
Security in .NET 2.0
Tracking down managed memory leaks
Handling exceptions in .NET
.NET Compact Framework graphics
The Data Access Application Block
A great .NET resource: .Net2TheMax
Delegates vs. interfaces in .NET
Project structure best practices

Platforms and Servers
Tracking down managed memory leaks
Handling exceptions in .NET
.NET Compact Framework graphics
The Data Access Application Block
Decision time: .NET or J2EE?
A great .NET resource: .Net2TheMax
Delegates vs. interfaces in .NET
Project structure best practices
Working with PDFs in a .NET environment
Displaying errors with the error provider

Microsoft .NET Web services
Microsoft preps .NET 4.0 - framework improves on REST, MVC, JQuery support
How do I balance throughput requirements and interoperability?
APM software traces transactions across tiers, technologies
How you can learn M Grammar for Oslo modeling
Legacy modernization opens Windows for publisher
Former .NET Web developers ride Ruby and Rails application framework
Microsoft Oslo at PDC: Dial 'M' for modeling language
Yahoo proxy fight looms
New Microsoft site for architects
LAMP coders go hybrid route
Microsoft .NET Web services Research

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
Common Language Infrastructure  (SearchSOA.com)
Visual J#  (SearchSOA.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary

DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.



SOA Trends and Strategy - SOA Education, SOA Development, SOA Implementations
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Site Map




All Rights Reserved, Copyright 2001 - 2009, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts