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

一、不带参数创建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

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

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

三、带多个参数创建Thread

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

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Threading; 
 
namespace CTest  
{ 
  class C
  { 
     public static void Main() 
     { 
        MyParam m = new MyParam(); 
        m.x = 6; 
        m.y = 9; 
 
        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=6,y=9

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

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

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Threading; 
 
namespace CTest  
{ 
  class C
  { 
     public static void Main() 
     { 
        MyParam m = new MyParam(); 
        m.x = 6; 
        m.y = 9; 
        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=6,y=9"); 
     } 
   } 
}

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值