Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用线程C#_C#_Multithreading - Fatal编程技术网

如何使用线程C#

如何使用线程C#,c#,multithreading,C#,Multithreading,我想知道我怎么能用线。 当我通过这段代码发出许多请求时,我的CPU使用率达到100% public static void GetPage(String url) { try { // Creates an HttpWebRequest for the specified URL. HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); // Sends the Htt

我想知道我怎么能用线。 当我通过这段代码发出许多请求时,我的CPU使用率达到100%

public static void GetPage(String url)
{
  try
  {
    // Creates an HttpWebRequest for the specified URL. 
    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);

    // Sends the HttpWebRequest and waits for a response.
    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

    if ( myHttpWebResponse.StatusCode == HttpStatusCode.OK )
      Console.WriteLine("\r\nResponse Status Code is OK and StatusDescription is: {0}",
                        myHttpWebResponse.StatusDescription);

    // Releases the resources of the response.
    myHttpWebResponse.Close();
  }
  catch ( WebException e )
  {
    MessegeBox.Show("\r\nWebException Raised. The following error occurred : {0}", e.Status);
  }
  catch ( Exception e )
  {
    MessegeBox.Show("\nThe following Exception was raised : {0}", e.Message);
  }
}

void myButton_Click(object sender, RoutedEventArgs e)
{
  new Thread(() =>
  {
    while ( true )
    {
      Getpage();
    }
    Thread.Sleep(1000);
  }
}
有没有办法让线程中止。
我想发送快速请求,这样我就不想在每次请求后进行多次休眠。

删除while循环,进程将停止以使CPU饱和

你不能从你的C代码中做任何事情

线程不是为了更快地完成任务,而是为了“同时”完成任务

您依赖于网络的基础结构和服务器的体系结构

试试这个:

void myButton_Click(object sender, RoutedEventArgs e)
{
  var thread = new Thread(() => { Getpage(someurl); });
  thread.Start();
}

等等,你说过“线程不是为了更快地完成任务,而是为了“同时”完成任务。”所以我必须使用异步等待是,建议不是为了进行扩展讨论;这段对话已经结束。