当我使用线程时-CPU使用率为100%

时间:2019-09-23 08:48:31

标签: c#

我尝试使用以下代码下载许多html页面,但是当我运行多线程时,我的CPU使用率为100%

using System.Net;
Thread thread = new Thread(t =>    
{
      while(true)
      {
        using (WebClient client = new WebClient ()) //
        {
         client.DownloadFile("http://dir.com/page.html", @"C:\localfile.html");
         string htmlCode = client.DownloadString("http://dir.com/page.html");
        }
      }
})
{ 
    IsBackground = true 
};
thread.Start();

我应该使用ThreadPool

1 个答案:

答案 0 :(得分:3)

您有一个while(true),中间没有睡觉。该线程将继续运行,并将消耗大量CPU能力。 (老实说,该页面不会每2毫秒更改一次。您一次又一次地下载同一页面。)

您应该进行某种限制,例如Thread.Sleep

while(true)
{
    using (WebClient client = new WebClient ()) //
    {
        string htmlCode = client.DownloadString("http://dir.com/page.html");

        File.WriteAllText(@"C:\localfile.html", htmlCode);
    }

    Thread.Sleep(60_000); // sleep for 60 seconds.
}