VS2005可以直接调用带参数的新线程方法 VS2003可以用类解决。class A () { public string a; public void Action1(string a); }需要线程调用时: A newa = new A(); newa.a = "abcd"; Thread newt = new Thread(new ThreadStart(newa.Action1)); newt.start();
首先谢谢各位楼上的朋友,现在的问题很奇怪我如果用不带参数的方法,就可以正常运行。而且使用冪名的方式都可以。例如: Thread newThread = new Thread(simp.Action1); newThread.Start();我看资料上说可以在start()方法中输入参数但是要使用ParameterizedThreadStart来说明委托。例如: Thread newThread = new Thread(new ParameterizedThreadStart(simp.Action1)); newThread.Start(2);但是我使用这个代码后系统提示 “Action1的重载与委托ParameterizedThreadStart不匹配”郁闷中。。
附上Action1()方法public void Action1(int jj) { for (int i = 0; i < 100; i++) { Console.WriteLine("线程名:"+Thread.CurrentThread.Name+i+" j="+jj); lock (this) { jj++; } } }
改为 public void Action1(object jj) { int _jj=(int)jj; for (int i = 0; i < 100; i++) { Console.WriteLine("线程名:"+Thread.CurrentThread.Name+i+" j="+_jj); lock (this) { _jj++; } } }
经过无数次的实验和查阅资料,也有有很多朋友的帮助。呵呵,我终于找到输入参数的方法了:)首先我们来定义被线程引用的方法 public class Simp { public void Action1(object jj) { for (int i = 0; i < 100; i++) { int j = Convert.ToInt16(jj); Console.WriteLine("线程名:"+Thread.CurrentThread.Name+i+" j="+j); lock (this) { j++; } } } } 重点是形参必须是“object ”类型的,不能是其他的类型。如果要对这个形参计算也必须要使用int j = Convert.ToInt16(jj)做类型转换说明线程时 Thread newThread = new Thread(new ParameterizedThreadStart(simp.Action1)); newThread.Name = "子线程1 : "; newThread.Start(20);在start方法中输入参数需要注意的是这里使用的是ParameterizedThreadStart,而不是ThreadStart 经过实验ThreadStart不能输入参数。
class A=new (1,2,3);
Thread objThread1 = new Thread(simp.Action1(a));
{
}
VS2003可以用类解决。class A ()
{
public string a;
public void Action1(string a);
}需要线程调用时:
A newa = new A();
newa.a = "abcd";
Thread newt = new Thread(new ThreadStart(newa.Action1));
newt.start();
Thread newThread = new Thread(simp.Action1);
newThread.Start();我看资料上说可以在start()方法中输入参数但是要使用ParameterizedThreadStart来说明委托。例如:
Thread newThread = new Thread(new ParameterizedThreadStart(simp.Action1));
newThread.Start(2);但是我使用这个代码后系统提示
“Action1的重载与委托ParameterizedThreadStart不匹配”郁闷中。。
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine("线程名:"+Thread.CurrentThread.Name+i+" j="+jj);
lock (this)
{
jj++;
}
}
}
public void Action1(object jj)
{
int _jj=(int)jj;
for (int i = 0; i < 100; i++)
{
Console.WriteLine("线程名:"+Thread.CurrentThread.Name+i+" j="+_jj);
lock (this)
{
_jj++;
}
}
}
public class Simp
{
public void Action1(object jj)
{
for (int i = 0; i < 100; i++)
{
int j = Convert.ToInt16(jj);
Console.WriteLine("线程名:"+Thread.CurrentThread.Name+i+" j="+j);
lock (this)
{
j++;
}
}
}
}
重点是形参必须是“object ”类型的,不能是其他的类型。如果要对这个形参计算也必须要使用int j = Convert.ToInt16(jj)做类型转换说明线程时
Thread newThread = new Thread(new ParameterizedThreadStart(simp.Action1));
newThread.Name = "子线程1 : ";
newThread.Start(20);在start方法中输入参数需要注意的是这里使用的是ParameterizedThreadStart,而不是ThreadStart
经过实验ThreadStart不能输入参数。