c#线程间传递参数

线程操作主要用到Thread类,他是定义在System.Threading.dll下。使用时需要添加这一个引用。该类提供给我们四个重载的构造函数(以下引自msdn)。

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

Thread (ThreadStart) 初始化 Thread 类的新实例。

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

Thread (ThreadStart, Int32) 初始化 Thread 类的新实例,指定线程的最大堆栈大小。

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

一、不带参数的

[c-sharp]view plaincopy

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. namespace AAAAAA
  6. {
  7. class AAA
  8. {
  9. public static void Main()
  10. {
  11. Thread t = new Thread(new ThreadStart(A));
  12. t.Start();
  13. Console.Read();
  14. }
  15. private static void A()
  16. {
  17. Console.WriteLine("Method A!");
  18. }
  19. }
  20. }

结果显示Method A!

二、带一个参数的

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

[c-sharp]view plaincopy

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. namespace AAAAAA
  6. {
  7. class AAA
  8. {
  9. public static void Main()
  10. {
  11. Thread t = new Thread(new ParameterizedThreadStart(B));
  12. t.Start("B");
  13. Console.Read();
  14. }
  15. private static void B(object obj)
  16. {
  17. Console.WriteLine("Method {0}!",obj.ToString ());
  18. }
  19. }
  20. }

结果显示Method B!

三、带多个参数的

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

[c-sharp]view plaincopy

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. namespace AAAAAA
  6. {
  7. class AAA
  8. {
  9. public static void Main()
  10. {
  11. My m = new My();
  12. m.x = 2;
  13. m.y = 3;
  14. Thread t = new Thread(new ThreadStart(m.C));
  15. t.Start();
  16. Console.Read();
  17. }
  18. }
  19. class My
  20. {
  21. public int x, y;
  22. public void C()
  23. {
  24. Console.WriteLine("x={0},y={1}", this.x, this.y);
  25. }
  26. }
  27. }

结果显示x=2,y=3

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

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

[c-sharp]view plaincopy

  1. //结构体
  2. struct RowCol
  3. {
  4. public int row;
  5. public int col;
  6. };
  7. //定义方法
  8. public void Output(Object rc)
  9. {
  10. RowCol rowCol = (RowCol)rc;
  11. for (int i = 0; i < rowCol.row; i++)
  12. {
  13. for (int j = 0; j < rowCol.col; j++)
  14. Console.Write("{0} ", _char);
  15. Console.Write("/n");
  16. }
  17. }