PrateekSaluja
PrateekSaluja

Reputation: 14926

How to call a method that takes multiple parameters in a thread?

I am building a C# Desktop application. How do I call a method that takes multiple parameters in a thread. I have a method called Send(string arg1, string arg2, string arg3) , I need to call this method using a thread called SendingThread. Can anyone help out with this? Any help will be much appreciated.

Upvotes: 11

Views: 13516

Answers (4)

sumit_batcoder
sumit_batcoder

Reputation: 3379

this may help. You can define your Send method as follows and then can use the parameters.

string[] parameters = new string[3];
parameters[0] = arg1;
parameters[1] = arg2;
parameters[1] = arg3;

System.Threading.Thread SendingThread = new System.Threading.Thread(Send);
SendingThread.Start(parameters);


public void Send(object parameters)
{
   Array arrayParameters = new object[3];
   arrayParameters = (Array)parameters;
   string str1 = (string)arrayParameters.GetValue(0);
   string str2 = (string)arrayParameters.GetValue(1);
   string str3 = (string)arrayParameters.GetValue(2);

   ///Following code here...
}

Upvotes: -1

Timwi
Timwi

Reputation: 66573

Thread thread = new Thread(() => Send(arg1, arg2, arg3));
thread.Start();

Upvotes: 23

Ronald Wildenberg
Ronald Wildenberg

Reputation: 32094

You can define an intermediate method and helper object to do this:

public void MethodToCallInThread(string param1, string param2)
{
    ...
}
public void HelperMethod(object helper){
    var h = (HelperObject) helper;
    MethodToCallInThread(h.param1, h.param2);
}

And then you start the thread with the HelperMethod, not with MethodToCallInThread:

var h = new HelperObject { param1 = p1, param2 = p2 }
ThreadPool.QueueUserWorkItem(HelperMethod, h);

Upvotes: 1

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

You could define a type, that encapsulates the parameters you want to pass and start the thread with a reference to an instance of this type.

Upvotes: 2

Related Questions