首页 > 开发 > 综合 > 正文

关于线程的参数、"返回值"、及线程的中止

2024-07-21 02:28:34
字体:
来源:转载
供稿:网友

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

菜鸟学堂:
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表