不堵塞CPU负载的方法

时间:2016-11-16 07:36:12

标签: c# cpu-usage

我相信如果我编写一个使用while(1){...}并运行它的程序,它会使CPU负载达到100%(这是真的吗?我已经完成了这个,而且发生了这种情况)。我也相信,也许在编写TCP程序时,使用阻塞连接功能时,也会发生这种情况。

ManualResetEventWaitOne()怎么样? ThreadSleep()函数会发生什么?这会阻塞CPU吗?

我有以下代码框架:

namespace SomeNamespace
    {

        class Program
         {
         private static volatile bool keepRunning = true;
         private static System.Threading.ManualResetEvent connectDone = new System.Threading.ManualResetEvent(false);

         static void Main(string[] args)
            {
              while(keepRunning)
                 {

                  //Here some code to create a socket client

                  try
                    {
                        connectDone.Reset();  //not signaled

                        Console.WriteLine("Trying to connect...");
                        clientSocket.BeginConnect("127.0.0.1", 4242, new AsyncCallback(OnConnect), clientSocket);

                        //wait here until the callback processes the connection

                        connectDone.WaitOne();  //<---HERE!!!

                        //Some more other code
                     }
                   catch(Exception e)
                    {
                      Console.WriteLine("Error");
                    }

                    //Here do some more processing and eventually

                     if (clientSocket.Connected)
                    {
                        Console.WriteLine("Closing the socket");
                        clientSocket.Close();
                     }
                }
         }//Main

          //The callback for asynchronous connect
            private static void OnConnect(IAsyncResult ar)
            {
                try
                {
                    //retrieve the client from the state object
                    TcpClient clientSocket = (TcpClient)ar.AsyncState;

                    //complete the connection
                    clientSocket.EndConnect(ar);

                    Console.WriteLine("Successfully Connected");

                }
                catch (Exception e)
                {
                    Console.WriteLine("Error on End Connect: {0}", e.Message);

                }
                finally
                {
                    connectDone.Set();
                }
            }



      }
    }

代码不完整但基本上使用异步连接。我想问的是1)这将特别在这里阻塞CPU 2)!部分将WaitOne阻塞CPU? WaitOne对资源使用的影响是什么?

如果我使用(不同的代码)ThreadSleep怎么样?这会影响CPU负载吗?

(我问这不是出于好奇心,而是因为我遇到的问题是CPU只在一台计算机上运行程序时使用100%资源而在其他计算机上没有 - 基本上是连接失败时的上述程序。成功没有障碍)

1 个答案:

答案 0 :(得分:1)

Socket.Connect的阻塞调用不会“堵塞”CPU,因为线程处于休眠状态,等待I / O操作完成。实际上,几乎所有的I / O操作都是这种情况,而不仅仅是打开一个套接字。如果您担心的是CPU负载 - 那么就不需要进行异步I / O.

ManualResetEvent.WaitOne也是如此。事实上,你在等待的事情实际上是将异步I / O转换回同步(阻塞)。

while(true)导致CPU负载的原因是因为线程不是等待信号从睡眠中唤醒,而是主动检查操作的完成,执行工作 - 它在{{{ 3}}。这可以通过允许线程在循环中稍微休眠来解决。虽然你最好不要创建自旋锁,并采用其他同步方法。

相关问题