当前位置: 移动技术网 > IT编程>开发语言>c# > C#往线程里传递参数的方法小结

C#往线程里传递参数的方法小结

2019年07月18日  | 移动技术网IT编程  | 我要评论

传参方式有两种:

1、创建带参构造方法类 传参

2、利用thread.start(8)直接传参,该方法会接收一个对象,并将该对象传递给线程,因此在线程中启动的方法

必须接收object类型的单个参数。

thread (parameterizedthreadstart) 初始化 thread 类的新实例,指定允许对象在线程启动时传递给线程的委托。

thread (threadstart) 初始化 thread 类的新实例。

由 .net compact framework 支持。

thread (parameterizedthreadstart, int32) 初始化 thread 类的新实例,指定允许对象在线程启动时传递给线程的委托,并指定线程的最大堆栈大小。

thread (threadstart, int32) 初始化 thread 类的新实例,指定线程的最大堆栈大小。

由 .net compact framework 支持。

我们如果定义不带参数的线程,可以用threadstart,带一个参数的用parameterizedthreadstart。带多个参数的用另外的方法,下面逐一讲述。

一、不带参数的

using system; 
using system.collections.generic; 
using system.text; 
using system.threading; 
namespace aaaaaa 
{ 
class aaa 
{ 
public static void main() 
{ 
thread t = new thread(new threadstart(a)); 
t.start(); 
console.read(); 
} 
private static void a() 
{ 
console.writeline("method a!"); 
} 
} 
} 

结果显示method a!

二、带一个参数的

由于parameterizedthreadstart要求参数类型必须为object,所以定义的方法b形参类型必须为object。

using system; 
using system.collections.generic; 
using system.text; 
using system.threading; 
namespace aaaaaa 
{ 
class aaa 
{ 
public static void main() 
{ 
thread t = new thread(new parameterizedthreadstart(b)); 
t.start("b"); 
console.read(); 
} 
private static void b(object obj) 
{ 
console.writeline("method {0}!",obj.tostring ()); 
} 
} 
} 

结果显示method b!

三、带多个参数的

由于thread默认只提供了这两种构造函数,如果需要传递多个参数,我们可以自己将参数作为类的属性。定义类的对象时候实例化这个属性,然后进行操作。

using system; 
using system.collections.generic; 
using system.text; 
using system.threading; 
namespace aaaaaa 
{ 
class aaa 
{ 
public static void main() 
{ 
my m = new my(); 
m.x = 2; 
m.y = 3; 
thread t = new thread(new threadstart(m.c)); 
t.start(); 
console.read(); 
} 
} 
class my 
{ 
public int x, y; 
public void c() 
{ 
console.writeline("x={0},y={1}", this.x, this.y); 
} 
} 
} 

结果显示x=2,y=3

四、利用结构体给参数传值。

定义公用的public struct,里面可以定义自己需要的参数,然后在需要添加线程的时候,可以定义结构体的实例。

//结构体 
struct rowcol 
{ 
public int row; 
public int col; 
}; 
//定义方法 
public void output(object rc) 
{ 
rowcol rowcol = (rowcol)rc; 
for (int i = 0; i < rowcol.row; i++) 
{ 
for (int j = 0; j < rowcol.col; j++) 
console.write("{0} ", _char); 
console.write("\n"); 
} 
} 

以上所述是小编给大家介绍的c#往线程里传递参数的方法小结,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网