關于線程的參數(2.0)、“返回值”、及線程的中止
1.線程的參數:
有時候會想向輔助線程傳遞些信息,這里需要用到ParameterizedThreadStart 委托
示例:
PRivate void btRunThread_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ParameterizedThreadStart(this.ThreadRun));
t.Start(100);
}
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://m.survivalescaperooms.com/KissKnife/archive/2006/10/03/520463.html
新聞熱點
疑難解答