C#------主线程和子线程如何实现互相传递数据

主线程和子线程如何实现互相传递数据

在C#中创建线程Thread时,可以有多种方法,而主线程和子线程之间又如何实现互相传递数据,每种创建方法传递参数的效果是不同的,逐一看一下:

一、不带参数创建Thread


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

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

二、带一个参数创建Thread

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

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Threading; 
 
namespace BTestThread  
{ 
  class BThread
  { 
     public static void Main() 
     {  
        Thread t = new Thread(new ParameterizedThreadStart(BThread)); 
        t.Start("B"); 
 
        Console.Read(); 
      } 
 
      private static void BThread(object obj) 
      { 
        Console.WriteLine("带一个参数 {0}!",obj.ToString ());  
      } 
   } 
}
结果显示“带一个参数 BThread!”

三、带多个参数创建Thread

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

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Threading; 
 
namespace CTestThread  
{ 
  class C
  { 
     public static void Main() 
     { 
        MyParam m = new MyParam(); 
        m.x = 1; 
        m.y = 2; 
 
        Thread t = new Thread(new ThreadStart(m.Test)); 
        t.Start(); 
 
        Console.Read(); 
      } 
  } 
  
  class MyParam  
  { 
     public int x, y; 
 
     public void Test() 
     { 
         Console.WriteLine("x={0},y={1}", this.x, this.y); 
     } 
   } 
}
结果显示“x=1,y=2”  

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

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Threading; 
 
namespace CTestThread  
{ 
  class CThread
  { 
     public static void Main() 
     { 
        MyParam m = new MyParam(); 
        m.x = 1; 
        m.y = 2; 
        m.callBack = ThreadCallBack;
 
        Thread t = new Thread(new ThreadStart(m.Test)); 
        t.Start(); 
 
        Console.Read(); 
     } 
  } 

  private void ThreadCallBack(string msg)
  {
     Console.WriteLine("CallBack:" + msg);  
  }
 
  private delegate void ThreadCallBackDelegate(string msg);

  class MyParam  
  { 
     public int x, y; 
     public ThreadCallBackDelegate callBack;
 
     public void Test() 
     { 
        callBack("x=1,y=2"); 
     } 
   } 
}
结果显示“CallBack:x=1,y=2”
posted @ 2022-10-21 15:42  郝阳坤  阅读(510)  评论(0编辑  收藏  举报