开发者社区 问答 正文

如何使用线程C#

我想知道如何使用线程。当我通过此代码发出许多请求时,我的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); } } 有什么办法可以使线程然后中止。我想发送快速请求,所以我不想在每次请求后进行多次睡眠。

展开
收起
被纵养的懒猫 2019-09-29 18:25:41 524 分享 版权
阿里云 AI 助理回答

在您的代码中,您创建了一个无限循环的线程来不断调用GetPage方法,并且在每次循环后让线程睡眠1秒。这确实不是一个高效处理大量网络请求的方式,尤其是当它导致CPU使用率激增时。为了更有效地管理并发和资源,您可以考虑以下几种改进策略:

1. 使用Taskasync/await

C#提供了异步编程模型,允许您以非阻塞方式执行I/O密集型操作,如HTTP请求,这样可以避免不必要的线程等待,减少CPU负担。

修改GetPage方法为异步版本:

public static async Task GetPageAsync(string url)
{
    try
    {
        using (var myHttpWebRequest = WebRequest.Create(url) as HttpWebRequest)
        {
            using (var myHttpWebResponse = await myHttpWebRequest.GetResponseAsync() as HttpWebResponse)
            {
                if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
                {
                    Console.WriteLine("\r\nResponse Status Code is OK and StatusDescription is: {0}", myHttpWebResponse.StatusDescription);
                }
            }
        }
    }
    catch (WebException e)
    {
        MessageBox.Show($"\r\nWebException Raised. The following error occurred : {e.Status}");
    }
    catch (Exception e)
    {
        MessageBox.Show($"\nThe following Exception was raised : {e.Message}");
    }
}

然后,在按钮点击事件中,您可以使用Task来并发地发送请求,但请注意控制并发数量以避免对服务器造成过大压力:

private async void myButton_Click(object sender, RoutedEventArgs e)
{
    const int MaxDegreeOfParallelism = 10; // 根据实际情况调整并发数
    var urls = new List<string> { /* 您的URL列表 */ };
    var semaphoreSlim = new SemaphoreSlim(MaxDegreeOfParallelism);

    foreach (var url in urls)
    {
        await semaphoreSlim.WaitAsync();
        _ = Task.Run(async () =>
        {
            try
            {
                await GetPageAsync(url);
            }
            finally
            {
                semaphoreSlim.Release();
            }
        });
    }

    // 等待所有任务完成(可选,取决于是否需要等待所有请求完成)
    // await Task.WhenAll(tasks);
}

2. 使用HttpClient替代WebRequest

HttpClient是.NET推荐用于发送HTTP请求的类,相比WebRequest提供了更好的性能和易用性。

3. 控制并发

通过SemaphoreSlim或类似机制限制并发请求数量,避免因过多并发导致的资源耗尽或服务器压力过大。

4. 错误处理与日志记录

确保有适当的错误处理逻辑,并考虑将异常信息写入日志文件而不是直接显示消息框,以便于问题排查。

采用上述方法,您不仅可以有效降低CPU使用率,还能提高程序处理网络请求的效率和响应速度。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答分类:
C#
问答地址: