C#多线程间传入值和返回值问题
不喜欢说那么多废话,直接上代码,不懂看注释!站在代码面前,一切问题将不再是问题!
一、不带参数的线程class main
{
public static void main(string[] args)
{
Thread th1 =new Thread(DoWork);
th1.Start();Thread th2
{
public static void main(string[] args)
{
Thread th1 =new Thread(DoWork);
th1.Start();Thread th2
=new Thread(new ParameterizedThreadStart(DoWorkWithParam));
object data =null;
th2.Start(data);
}
privatevoid DoWork()
{
//do something
}
privatevoid DoWorkWithParam(object param)
{
string data = param.ToString();
//do something
}}
二、带一个参数
class main
{
public static void main(string[] args)
{
Thread th2 =new Thread(new ParameterizedThreadStart(DoWorkWithParam));
object data =null;
th2.Start(data);
}
privatevoid DoWorkWithParam(object param)
{
string data = param.ToString();
//do something
}}
三、带两个及两个以上的参数
publicclass ThreadWithParams {
privatestring param1;
privateintparam2;public ThreadWithParams(string param1, int param2 )
{
this. param1 = param1 ;
this. param2 = param2;
}
privatestring param1;
privateintparam2;public ThreadWithParams(string param1, int param2 )
{
this. param1 = param1 ;
this. param2 = param2;
}
publicvoid ThreadProc()
{
Console.WriteLine(param1, param2);
}
}
publicclass Main{
publicstaticvoid Main()
{
//初始化两个参数
ThreadWithParams twp =new ThreadWithState( "i am param1", 2);
Thread t =new Thread(new ThreadStart(twp.ThreadProc));
t.Start();
}
}
ThreadWithParams twp =new ThreadWithState( "i am param1", 2);
Thread t =new Thread(new ThreadStart(twp.ThreadProc));
t.Start();
}
}