thread with multiple parameters

Viewed 90513

Does anyone know how to pass multiple parameters into a Thread.Start routine?

I thought of extending the class, but the C# Thread class is sealed.

Here is what I think the code would look like:

...
    Thread standardTCPServerThread = new Thread(startSocketServerAsThread);

    standardServerThread.Start( orchestrator, initializeMemberBalance, arg, 60000);
...
}

static void startSocketServerAsThread(ServiceOrchestrator orchestrator, List<int> memberBalances, string arg, int port)
{
  startSocketServer(orchestrator, memberBalances, arg, port);
}

BTW, I start a number of threads with different orchestrators, balances and ports. Please consider thread safety also.

11 Answers

Try using a lambda expression to capture the arguments.

Thread standardTCPServerThread = 
  new Thread(
    unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)
  );

You need to wrap them into a single object.

Making a custom class to pass in your parameters is one option. You can also use an array or list of objects, and set all of your parameters in that.

Use the 'Task' pattern:

public class MyTask
{
   string _a;
   int _b;
   int _c;
   float _d;

   public event EventHandler Finished;

   public MyTask( string a, int b, int c, float d )
   {
      _a = a;
      _b = b;
      _c = c;
      _d = d;
   }

   public void DoWork()
   {
       Thread t = new Thread(new ThreadStart(DoWorkCore));
       t.Start();
   }

   private void DoWorkCore()
   {
      // do some stuff
      OnFinished();
   }

   protected virtual void OnFinished()
   {
      // raise finished in a threadsafe way 
   }
}

You can't. Create an object that contain params you need, and pass is it. In the thread function cast the object back to its type.

You can take Object array and pass it in the thread. Pass

System.Threading.ParameterizedThreadStart(yourFunctionAddressWhichContailMultipleParameters) 

Into thread constructor.

yourFunctionAddressWhichContailMultipleParameters(object[])

You already set all the value in objArray.

you need to abcThread.Start(objectArray)

You could curry the "work" function with a lambda expression:

public void StartThread()
{
    // ...
    Thread standardTCPServerThread = new Thread(
        () => standardServerThread.Start(/* whatever arguments */));

    standardTCPServerThread.Start();
}
Related