zoukankan      html  css  js  c++  java
  • 多线程实例,占用CPU过多

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

    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%.

     

  • 相关阅读:
    Web crawler study(1)
    SNMP
    Locked the resolv.conf via command chattr
    HTML 父窗口打开子窗口,并从子窗口返回值
    混合语言学习(一)
    Auto Scale TextView Text to Fit within Bounds
    Android SeekBar size
    Android设置全局字体
    PopupMenu使用,PopupMenu背景的设置
    Android-屏幕适配全攻略
  • 原文地址:https://www.cnblogs.com/qq4004229/p/2246414.html
Copyright © 2011-2022 走看看