现在的位置: 首页 > 综合 > 正文

多线程实例,占用CPU过多

2012年11月08日 ⁄ 综合 ⁄ 共 1119字 ⁄ 字号 评论关闭

自已研究一下,有新发现,以前没发现这么多 

 

Thread mainThread;
        Thread childThread;
        private void btnRun_Click(object sender, EventArgs e)
        {
           mainThread = new Thread(()=>ReadThread());
            mainThread.IsBackground = true;
            mainThread.Start();
        }

        protected void ReadThread()
        {
            int works = 100;
            for (int i = 0; i < nums; i++)
            {
            
                childThread = new Thread(() => ToDoSth(works, i));
                childThread.IsBackground = true;
                childThread.Start();

            }

        }
        protected void ToDoSth(int works, int threads)
        {

            for (int i = 0; i < works; i++)
            {
                Application.DoEvents();
               Thread.Sleep(5000);
                this.Invoke((MethodInvoker)delegate
                {
                    listBox1.Items.Add(threads + ":" + System.DateTime.Now.ToString());
                });

                Application.DoEvents();

            }
        }

 

 

原因:程序中因为使用ThreadPool 多线程操作.Form.Invoke 用了很多,造成CPU占用 90%以上,甚至程序假死..... 我一度去掉所有lock数据库操作什么的代码,都没大的改善.....

解决方法:

每次调用完后. 让她睡个300毫秒(System.Threading.Thread.Sleep(300) ,你可以设置更小.) 整个世界清静了,CPU没超过10%.

 

 

 

抱歉!评论已关闭.