C#跨线程访问(二)----thread参数、回调传参数

时间:2019-11-25
本文章向大家介绍C#跨线程访问(二)----thread参数、回调传参数,主要包括C#跨线程访问(二)----thread参数、回调传参数使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、单个参数(封箱也可实现多参数)

class B
  { 
     public static void Main() 
     {  
        Thread t = new Thread(new ParameterizedThreadStart(Test)); 
        t.Start("a"); 
 
        Console.Read(); 
      } 
 
      private static void Test(object obj) 
      { 
        Console.WriteLine("带一个参数 {0}!",obj.ToString ());  
      } 
   } 
二、多个参数

 class Test2
  { 
     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); 
     } 
   } 

三、回调函数传参

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"); 
     } 
   } 

原文地址:https://www.cnblogs.com/xietianjiao/p/11929059.html