【转载】在C#中主线程和子线程如何实现互相传递数据?

引用:https://blog.csdn.net/shuaihj/article/details/41316731

一、不带参数创建Thread

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Threading; 
 
namespace ATest  
{ 
  class A  
  { 
     public static void Main() 
     { 
        Thread t = new Thread(new ThreadStart(A)); 
        t.Start(); 
 
        Console.Read(); 
      } 
 
      private static void A() 
      { 
         Console.WriteLine("不带参数 A!"); 
      } 
   } 
}

  结果显示“不带参数 A!”

二、带一个参数创建Thread

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

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

结果显示“带一个参数 B!”

三、带多个参数创建Thread

由于Thread默认只提供了这两种构造函数,如果需要传递多个参数,可以基于第二种方法,将参数作为类的属性传给线程。

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

结果显示“x=6,y=9”

四、利用回调函数给主线程传递参数

我们可以基于方法三,将回调函数作为类的一个方法传进线程,方便线程回调使用。

 1 using System; 
 2 using System.Collections.Generic; 
 3 using System.Text; 
 4 using System.Threading; 
 5  
 6 namespace CTest  
 7 { 
 8   class C
 9   { 
10      public static void Main() 
11      { 
12         MyParam m = new MyParam(); 
13         m.x = 6; 
14         m.y = 9; 
15         m.callBack = ThreadCallBack;
16  
17         Thread t = new Thread(new ThreadStart(m.Test)); 
18         t.Start(); 
19  
20         Console.Read(); 
21      } 
22   } 
23 
24   private void ThreadCallBack(string msg)
25   {
26      Console.WriteLine("CallBack:" + msg);  
27   }
28  
29   private delegate void ThreadCallBackDelegate(string msg);
30 
31   class MyParam  
32   { 
33      public int x, y; 
34      public ThreadCallBackDelegate callBack;
35  
36      public void Test() 
37      { 
38         callBack("x=6,y=9"); 
39      } 
40    } 
41 }

结果显示“CallBack:x=6,y=9”