Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)aaa
published in(发表于) 2013/12/6 10:26:42
关于线程的参数、“返回值”、及线程的中止_.net资料_编程技术

关于线程的参数、“返回值”、及线程的中止_.net资料_编程技术-数科优化网

关于线程的参数(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...");
}
}
}






If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759