C# 当我使用线程时,CPU使用率为100%

C# 当我使用线程时,CPU使用率为100%,c#,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",

我尝试使用下面的代码下载许多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

您有一个
while(true)
,中间没有任何睡眠。该线程将继续运行,并将消耗大量CPU资源。(老实说,页面不会每2毫秒更改一次。您正在反复下载同一页面。)

您应该有某种节流功能,如
线程。睡眠

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

为什么不使用webclient.downloadfileasync?为什么需要无休止的循环?下载的html页面不多,只有一个。你是在一个紧密的循环中完成这项工作的,所以难怪当你达到与你的(v)核数相等的线程数时,你会达到100%。但是当我在几秒钟后切换页面时,我的CPU会100%使用async/await,让框架为你管理它。你不在乎它是否在一个新的线程中运行,你只在乎它没有阻塞,因此async/await是最好的选择。为什么
60_000
intead
60000
,是拼写错误还是我不知道的魔法?是的,它是一个千位分隔符@随机的