關於執行緒的參數(2.0)、「回傳值」、及執行緒的中止
1.線程的參數:
有時候會想傳遞一些訊息,這裡需要用到ParameterizedThreadStart 委託
範例:
private void btRunThread_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ParameterizedThreadStart(this.ThreadRun) { Thread t.Start1 Thread(new ParameterizedThreadStart(this.ThreadRun))
; );
}
private void ThreadRun(object o)
{
this.lbCompleted.Invoke((MethodInvoker)delegate { this.lbCompleted.Text = System.Convert.ToString(o); });
}
2.透過代理可以大致實現類似功能,範例:
class Program
{
static void Main(string[] args)
{
ThreadClass tc = new ThreadClass(new MyDlg(DlgMethod));
Thread thread = new Thread(new ThreadStart(tc.ThreadRun ));
Console.WriteLine("second thread start");
thread.Start();
thread.Join();
Console.WriteLine("second thread completed");
Console.Read();
}
private static void DlgMethod(int i)
{
Console.WriteLine("Second Thread Result:{0}", i);
}
}
public delegate void MyDlg(int i);
class ThreadClass
{
private MyDlg myDlg;
public ThreadClass(MyDlg pDlg)
{
this.myDlg = pDlg;
}
public void ThreadRun()
{
int total = 0;
for (int i = 0; i < 100; i++)
{
total += i;
}
if (myDlg != null)
{
myDlg(total);
}
}
}
3.線程的中止:
(1).join方法
MSDN註釋:在繼續執行標準的COM 和SendMessage 訊息泵處理期間,阻止呼叫線程,直到某個線程終止為止。
看得一頭霧,自己試了一下,似乎線程在調用join方法之後,該線程搶佔了所有的cpu時間,直到線程的任務完成。不知道是這樣?
(2).abort方法
立即中止執行緒
(3).定義識別數量範例
:
class Program
{
private static bool stop;
static void Main(string[] args)
{
stop = false;
Thread t = new Thread(new ThreadStart(ThreadRun));
t.Start();
Thread.Sleep(100);
stop = true;
Console.Read();
}
static void ThreadRun()
{
while (!stop)
{
Console.WriteLine("Do Some Work...");
} }
}
}
http://www.cnblogs.com/KissKnife/archive/2006/10/03/520463.html