2013年8月21日 星期三

使用Thread

啟動Thread

Thread _runningThread =null;  
public void StartMainThread()  
{  
 try  
 {  
  if (_runningThread != null)  
  {  
   _runningThread.Abort();  
  }  
  _runningThread = new Thread(Go);     //也可以這樣寫_runningThread = new Thread(new ThreadStart(Go)); 
                _runningThread.IsBackground = true;  //設定thread在背景執行
  _runningThread.Start();  
 }  
 catch (Exception Ex)  
 {  
  Console.WriteLine(Ex.Message);  
 }  
}  

結束Thread

public void StopMainThread()  
{  
 try  
 {  
  if (_runningThread != null)  
  {  
   //stop Thread  
   _runningThread.Abort();  
   //Release resource  
   _runningThread = null;  
  }  
 }  
 catch (Exception Ex)  
 {  
  Console.WriteLine(Ex.Message);  
 }  
}  

Thread傳遞一個參數

Thread t = new Thread (new ParameterizedThreadStart (Go));  
t.Start (true);  
  
static void Go (object upperCase)  
{  
 bool upper = (bool) upperCase;  
 Console.WriteLine (upper ? "HELLO!" : "hello!");  
}  

Thread傳遞多個參數

方法一、使用委派

string words;  
string link;  
Thread _runningThread = new Thread(delegate() { Lookup(words, link); });  
_runningThread.Start(); 

方法一、使用類別

public class cc  
{  
 public int i;  
 public void ShowText()  
 {  
  i++;  
 }  
}   
  
private void button1_Click(object sender, System.EventArgs e)  
{  
 cc ac=new cc();  
 ac.i=0;  
 Thread a=new Thread(new ThreadStart(ac.ShowText));  
}  

沒有留言: