Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 963
PrateekSaluja Avatar asked Aug 30 '10 07:08

PrateekSaluja


3 Answers

Thread thread = new Thread(() => Send(arg1, arg2, arg3));
thread.Start();
like image 85
Timwi Avatar answered Oct 29 '22 10:10

Timwi


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.

like image 34
Brian Rasmussen Avatar answered Oct 29 '22 11:10

Brian Rasmussen


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);
like image 30
Ronald Wildenberg Avatar answered Oct 29 '22 12:10

Ronald Wildenberg