如何使用线程C#
我想知道我怎么能用线。 当我通过这段代码发出许多请求时,我的CPU使用率达到100%如何使用线程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
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();
}
等等,你说过“线程不是为了更快地完成任务,而是为了“同时”完成任务。”所以我必须使用异步等待是,建议不是为了进行扩展讨论;这段对话已经结束。