Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I am new to c# and threading.

I want to call more than two functions at the same time . So i am uisng threads

private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(connect));
t.Start();
Thread t1 = new Thread(new ThreadStart(connect1));
t1.Start();


}//click

when run like this , it is working.

If it is like this i have to repeat the code again.
What i thought is , i will change the same function with different parameter
so i did like this




private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(connectPara("sp1")));
t.Start();
Thread t1 = new Thread(new ThreadStart(connectPara("sp2")));
t1.Start();


}//click
i got this errors

Method name expected
The name 't' does not exist in the current context

1, I may need to call more than 5 or 6 threads later. So i am planning to use the same function with different parameters. what i need is to run functions with parameters in the thread
How can do with the threading.

2, One more doubt is how do i know that the the thread is executed fully or it got stucked some where in the middle

Can anybody help me resolve this issue
Posted

If you want to pass parameters to a function in a thread use this:

Thread th = new Thread(delegate()
{
      connectPara("sp1");
});
th.Start();
Thread th1 = new Thread(delegate()
{
      connectPara("sp2");
});
th1.Start();
 
Share this answer
 
v2
1) You can use a ParameterizedThreadStart and use the overload of Thread.Start that takes a parameter.

void connectPara( object o )
{
  var s = o as string; // this will be "sp1"

  ...
}

...
var t = new Thread( connectPara );
t.Start( "sp1" );
...


2) There are many ways to communicate between threads. If you just want to check if a thread has completed, you could use Thread.IsAlive or Thread.ThreadState.

Nick
 
Share this answer
 
1. The best way to pass parameters on thread start is to create a class with the variables and the method you would like to expose and then, invoke the method of the object instance (which holds the variables) http://www.yoda.arachsys.com/csharp/threadstart.html)

2. The status of the thread can be checked to determine if the thread competed or not. (Introduction to Threads in C#)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900