1. 程序中开了6,7个线程,运行的时候CPU占用率达到60%-70%,太高了,影响性能,用线程池可否优化。线程池我还没用过,大概知道这个名词。
2. 在退出程序的时候在Form_closing()方法中,让线程都终止,用的是让标志变量为fasle,当然没用Abort方法,有没有必要等到线程的IsAlive状态为false的时候再退出,程序中我是加了循环等待到IsAlive的状态为false再退出程序,但是这样会造成退出很慢,有时候还会出现死循环,线程的IsAlive迟迟不为false。起初这样做的原因是怕不等到线程彻底结束,造成不安全因素。
   还有我还试过,用标志变量让线程终止,等待线程的IsAlive状态为false后,线程就无法再开启,报ThreadStateException,IsAlive状态值始终为false。         if (threadJoyStickMaxon != null)  
           {
               while (threadJoyStickMaxon.IsAlive)
               {
                    Thread.Sleep(1);
              }
              threadJoyStickMaxon = null;
          }
          threadJoyStickMaxon = new Thread(new ThreadStart(ManageThreadJoystickMaxon));
          threadJoyStickMaxon.Start();

解决方案 »

  1.   

    1. 消耗高,线程池也拯救不了你,只能说你的处理太费CPU,和线程无直接关系,要么优化你的处理代码,要么拿时间换空间,在高频率循环处理的地方做Thread.Sleep,通过延长线程的处理时间来减低CPU的消耗;或者降低线程的并发数;
    2. threadJoyStickMaxon.IsBackground = true;
      

  2.   

    我把线程都设为后台线程,关闭窗口的时候不再等待线程的IsAlive属性为false,是快了2/3,但感觉还是有点卡。
      

  3.   

    你的线程执行的东西太耗时间和CPU吧,能把他分成几个任务来做不?
      

  4.   

    我不得不说你的代码“的蛋疼”!如果没事可做,过程就结束了。在线程调用方法中写 while 循环干什么?难道是想把 CPU 烧热地点好用来煮鸡蛋?比如说我们来接收客户端消息,那么向底层系统注册一个回调就行了,底层系统每当收到消息就会在一个系统线程池重分配一个线程来执行我们的回调方法。而我们的回调方法处理完这个消息(可能用时3毫秒)就自然地结束了。写什么while循环干什么?
      

  5.   

    你写一个while来奢侈地用CPU煮鸡蛋,然后千方百计地去搞什么优化,我觉得这种开发方法实在是难以“礼遇”啊。
      

  6.   

    实际上这反映的是一个软件工程基本知识问题。敏捷程序是“事件驱动”的,而我们监听底层系统的事件就是由底层系统来驱动我们的代码的。事件驱动,请记住这个概念。不是说我们写一大堆while去轮询底层系统。
      

  7.   

    大量资源浪费在 
     while (threadJoyStickMaxon.IsAlive)
                   {
                        Thread.Sleep(1);
                  }
    如何谈优化
      

  8.   

    这是在程序退出的时候判断线程的IsAlive是否为false,贴代码的时候while之前漏写一个标志变量了,所以问题问“退出程序时退出线程有没有必要等到线程的IsAlive为false再退出”。
      

  9.   

    我没有说“写一大堆while去轮询底层系统”,不用事件驱动。
      

  10.   

    只要你做任务处理完了。就可以退出。你可弄一个标志标志一下你的任务是否结束。只要结束了。就可以安全的结束线程,无论是abort还是你的这种IsAlive标志退出都是安全的。
      

  11.   

    第一步:做个管理类
    MemoryManagement.cs
    namespace AliwwJC
    {
        /// <summary>
        /// Author:king
        /// This class provide methods to automatic do the Memory Management, 
        /// free some resources and collect garbage
        /// </summary>
        public sealed class MemoryManagement : IDisposable
        {
            #region Properties
            /// <summary>
            /// Current app ticks
            /// </summary>
            private long _ticks;        /// <summary>
            /// Gets a value indicating if the Memory Management is stopped or running.
            /// </summary>
            private bool _hasStarted;        /// <summary>
            /// Gets a value indicating if the Memory Management is stopped or running.
            /// </summary>
            public bool HasStarted
            {
                get { return _hasStarted; }
            }        #endregion        #region Constructors        /// <summary>
            /// Initializes a new instance of the <see cref="T:ApplicationManagement.MemoryManagement"/> class. 
            /// Note: This class is only for Win32NT Operative Systems, static methods still can be used in both.
            /// </summary>
            /// <param name="start">If true initializes the class and starts the memory management, 
            /// otherwise only initializes the class</param>
            /// <res>If that class is used in a unsupported Operative System, nothing will happen.</res>
            public MemoryManagement(bool start)
            {
                if (start)
                    Start();
            }        /// <summary>
            /// Initializes a new instance of the <see cref="T:ApplicationManagement.MemoryManagement"/> class. 
            /// Note: This class is only for Win32NT Operative Systems, static methods still can be used in both.
            /// </summary>
            /// <res>If that class is used in a unsupported Operative System, nothing will happen.</res>
            public MemoryManagement()
            {
            }        #endregion        #region Public Methods        /// <summary>
            /// Starts the automatic memory management.
            /// </summary>
            /// <returns>Returns true if function starts successful, otherwise false.</returns>
            public bool Start()
            {
                if (_hasStarted || Environment.OSVersion.Platform != PlatformID.Win32NT)
                    return false;
                _ticks = DateTime.Now.Ticks;
                Application.Idle += Application_Idle;
                Free();
                _hasStarted = true;
                return true;
            }        /// <summary>
            /// Stops the automatic memory management.
            /// </summary>
            /// <returns>Returns true if function stops successful, otherwise false.</returns>
            public bool Stop()
            {
                if (!_hasStarted)
                    return false;
                Application.Idle -= Application_Idle;
                _ticks = 0;
                _hasStarted = false;
                return true;
            }        #endregion        #region Static Methods        /// <summary>
            /// Free resources.
            /// </summary>
            private static void Free()
            {
                try
                {
                    using (Process proc = Process.GetCurrentProcess())
                    {
                        Kernel32.SetProcessWorkingSetSize(proc.Handle, -1, -1);
                    }
                }
                catch (Exception)
                {
                }        }        /// <summary>
            /// Gets if this class <see cref="MemoryManagement"/> can be used. 
            /// </summary>
            /// <returns>Returns true if this class can be used under current Operative System, otherwise false.</returns>
            public static bool CanUseClass()
            {
                return Environment.OSVersion.Platform == PlatformID.Win32NT;
            }        #endregion
      

  12.   

            #region Public Static Methods        /// <summary>
            /// Collect Garbage and free memory.
            /// </summary>
            public static void CollectGarbage()
            {
                GC.Collect(0);
                GC.GetTotalMemory(false);
                GC.Collect(0);
            }        #endregion        #region Event Methods        /// <summary>
            /// When application is idle, this event is fired.
            /// </summary>
            /// <param name="sender">Sender object.</param>
            /// <param name="e">Event aruments.</param>
            private void Application_Idle(object sender, EventArgs e)
            {
                try
                {
                    long ticks = DateTime.Now.Ticks;
                    if ((ticks - _ticks) > 0x989680L)
                    {
                        _ticks = ticks;
                        Free();
                    }
                }
                catch
                {
                }
            }        #endregion        #region Implementation of IDisposable        /// <summary>
            /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
            /// </summary>
            /// <filterpriority>2</filterpriority>
            public void Dispose()
            {
                Stop();
            }        #endregion
        }
    }