Passing Parameters to Threads

Posted on 5/27/2007 @ 4:47 PM in #Bak2Basics by | Feedback | 16590 views

How do you start a new thread in .NET 1.1? Well, it's easy, you use Thread.Start. The problem is, the constructor for System.Threading.Thread takes in a parameter called ThreadStart, which is a delegate. So a typical usage is as below.

using System;
using System.Threading;

public class ThreadWork 
{
   
public static void DoWork()
   {
      
for(int i = 0; i<3;i++)
      {
         Console.WriteLine("Working thread...");
            Thread.Sleep(100);
      }
   }
}
class ThreadTest
{
   
public static void Main()
   {
      ThreadStart myThreadDelegate = 
new ThreadStart(ThreadWork.DoWork);
      Thread myThread = 
new Thread(myThreadDelegate);
      myThread.Start();
         
for(int i = 0; i<3; i++)
         {
         Console.WriteLine("In main.");
            Thread.Sleep(100);
         }
   }
}

 

The problem is, the address that may hold, is of a function that takes in no parameters. That's all hunky dory, except if you need to have a mechanism to pass in your own parameters to the thread, you need to jump through a few hoops.

NO MORE in .NET 2.0, where you have a new thing called ParameterizedThreadStart. A typical usage pattern excerpt is as below.

Thread myThread;
myThread = 
   
new System.Threading.Thread(new ParameterizedThreadStart(ThreadEntryPoint));
Transaction currentTransactionClone = Transaction.Current.Clone();
myThread.Start(currentTransactionClone);

In the above code, the ThreadEntryPoint simply looks like as shown below.

private static void ThreadEntryPoint(object transactionInstance)
{
   isThreadRunning = 
true ;
   Transaction currentTransactionClone = (Transaction)transactionInstance;
   
using (SqlConnection connection2 = new SqlConnection(connectionString2))
   {
      connection2.Open();
      connection2.EnlistTransaction(currentTransactionClone);
      
// Do something here - this connection is manually enlisted.
      
currentTransactionClone.Rollback(); // ok to do
   
}
   isThreadRunning = 
false ;
}

The above code is running ThreadEntryPoint in a different thread, and is able to pass in an object - that is basically a copy of a System.Transactions.Transaction. What the above code is demonstrating is the ability of being able to pass a System.Transactions.Transaction clone on a different thread - and that a cloned transaction can only be rolled back from the other thread, but not committed.

BTW, also check out the BackgroundThreadWorker

Sound off but keep it civil:

Older comments..