.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...");

            }

        }

    }

 

 

posted @ 2006-10-03 11:27  后厂村思维导图馆  阅读(2149)  评论(1编辑  收藏  举报