I like to call the method in thread with arguments and return some value here example
class Program
{
static void Main()
{
Thread FirstThread = new Thread(new ThreadStart(Fun1));
Thread SecondThread = new Thread(new ThreadStart(Fun2));
FirstThread.Start();
SecondThread.Start();
}
public static void Fun1()
{
for (int i = 1; i <= 1000; i++)
{
Console.WriteLine("Fun1 writes:{0}", i);
}
}
public static void Fun2()
{
for (int i = 1000; i >= 6; i--)
{
Console.WriteLine("Fun2 writes:{0}", i);
}
}
}
I know this above example run successfully but if method fun1 like this
public int fun1(int i,int j)
{
int k;
k=i+j;
return k;
}
then how can I call this in thread?
I like Mark Gravell's answer. You can pass your result back out to the main thread with just a little modification:
You can use the ParameterizedThreadStart overload on the Thread constructor. It allows you to pass an Object as a parameter to your thread method. It's going to be a single Object parameter, so I usually create a parameter class for such threads.. This object can also store the result of the thread execution, that you can read after the thread has ended.
Don't forget that accessing this object while the thread is running is possible, but is not "thread safe". You know the drill :)
Here's an example:
For some alternatives; currying:
or write your own capture-type (this is broadly comparable to what the compiler does for you when you use anon-methods / lambdas with captured variables, but has been implemented differently):
There is much simpler way to execute function in separate thread:
This function will be executed on thread pool thread, and that logic is completely transparent to your application. An in general, I suggest to execute such small tasks on thread pool instead of dedicated thread.
try backgroundWorker http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx you can pass value to the DoWork event with DoWorkEventArgs and retrive value in the RunWorkerCompleted.
This may be another approach. Here input is passed as parameterized Thread and return type is passed in the delegate event, so that when the thread complete that will call the Delegate. This will be fine to get result when the thread completes.