Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

creating threads in C#

Status
Not open for further replies.

thedougster

Programmer
Jan 22, 2009
56
US
Can someone please break down a simple statement for a relative newbie?

Code:
Thread firstThread = new Thread (new ThreadStart (Method1));

In other words, what is happening at each stage here:

Code:
new ThreadStart (Method1)

Code:
new Thread (new ThreadStart (Method1))

Code:
Thread firstThread = new Thread (new ThreadStart (Method1));

Thanks for any help you can give.
 

Method1 is the actual work you want done.
Code:
new ThreadStart (Method1)
this is the delegate that references the work to be done.
Code:
new Thread (new ThreadStart (Method1))
creates a new thread that references the delegate... which references the actual work
Code:
Thread firstThread = new Thread (new ThreadStart (Method1));
the only difference between this snippet and previous one is the language syntax VB vs C#. and C# is assigning the instance to a variable, but you would need that in VB too.
Code:
Thread firstThread = new Thread (new ThreadStart (Method1));
firstThread.Start();
actually executes the Method1 call.

Threading gets very complex very quickly there are a number of issues to consider.
1. Exception Handling
2. Ensure no Cross Thread References
3. getting the return value, if there is one.

the BackgroundWorkerProcess object abstracts some of the raw threading details away and has hooks to get at return values and exceptions.

another, more robust option, is a full service bus framework like:
NServiceBus
Rhino.ServiceBus
MassTransit

all are OSS projects with strong communities.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top