關(guān)于線程的參數(shù)(2.0)、“返回值”、及線程的中止
1.線程的參數(shù):
有時(shí)候會(huì)想向輔助線程傳遞些信息,這里需要用到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.通過代理可以大致實(shí)現(xiàn)類似功能,示例:
    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注釋:在繼續(xù)執(zhí)行標(biāo)準(zhǔn)的 com 和 sendmessage 消息泵處理期間,阻止調(diào)用線程,直到某個(gè)線程終止為止。
看得一頭霧,自己試了一下,似乎線程在調(diào)用join方法之后,該線程搶占了所有的cpu時(shí)間,直到線程的任務(wù)完成。不知道是這是這樣?
(2).abort方法
立即中止線程
(3).定義標(biāo)識(shí)量
示例:
    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...");
            }
        }
    }
新聞熱點(diǎn)
疑難解答
圖片精選