2010年12月30日 星期四

使用Thread

啟動Thread與結束Thread
Thread _runningThread =null;
public void StartMainThread()
{
try
{
if (_runningThread != null)
{
_runningThread.Abort();
}
_runningThread = new Thread(Go);
_runningThread.Start();
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
}
}

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

沒有留言: