1. 程式人生 > >C#多執行緒呼叫有參的方法

C#多執行緒呼叫有參的方法

Thread (ParameterizedThreadStart) 初始化 Thread 類的新例項,指定允許物件線上程啟動時傳遞給執行緒的委託。   
Thread (ThreadStart) 初始化 Thread 類的新例項。  
由 .NET Compact Framework 支援。  
Thread (ParameterizedThreadStart, Int32) 初始化 Thread 類的新例項,指定允許物件線上程啟動時傳遞給執行緒的委託,並指定執行緒的最大堆疊大小。   
Thread (ThreadStart, Int32) 初始化 Thread 類的新例項,指定執行緒的最大堆疊大小。  
由 .NET Compact Framework 支援。  
  我們如果定義不帶引數的執行緒,可以用ThreadStart,帶一個引數的用ParameterizedThreadStart。帶多個引數的用另外的方法,下面逐一講述。  

一、不帶引數的 

using System;  
using System.Collections.Generic;  
using System.Text;  
using System.Threading;  
 
namespace AAAAAA  
{  
  class AAA  
  {  
  public static void Main()  
  {  
  Thread t = new Thread(new ThreadStart(A));  
  t.Start();  
 
  Console.Read();  
  }  
 
  private static void A()  
  {  
  Console.WriteLine("Method A!");  
  }  
  }  
}

結果顯示Method A! 

二、帶一個引數的  

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

結果顯示Method B! 

三、帶多個引數的  
  由於Thread預設只提供了這兩種建構函式,如果需要傳遞多個引數,我們可以自己將引數作為類的屬性。定義類的物件時候例項化這個屬性,然後進行操作。 

using System;  
using System.Collections.Generic;  
using System.Text;  
using System.Threading;  
 
namespace AAAAAA  
{  
  class AAA  
  {  
  public static void Main()  
  {  
  My m = new My();  
  m.x = 2;  
  m.y = 3;  
 
  Thread t = new Thread(new ThreadStart(m.C));  
  t.Start();  
 
  Console.Read();  
  }  
  }  
 
  class My  
  {  
  public int x, y;  
 
  public void C()  
  {  
  Console.WriteLine("x={0},y={1}", this.x, this.y);  
  }  
  }  
}

結果顯示x=2,y=3 

四、利用結構體給引數傳值。  
定義公用的public struct,裡面可以定義自己需要的引數,然後在需要新增執行緒的時候,可以定義結構體的例項。

//結構體  
  struct RowCol  
  {  
  public int row;  
  public int col;  
  };  
 
//定義方法  
public void Output(Object rc)  
  {  
  RowCol rowCol = (RowCol)rc;  
  for (int i = 0; i < rowCol.row; i++)  
  {  
  for (int j = 0; j < rowCol.col; j++)  
  Console.Write("{0} ", _char);  
  Console.Write("\n");  
  }  
  }