gpt4 book ai didi

c# - sleep 线程无法正常工作

转载 作者:可可西里 更新时间:2023-11-01 16:56:14 24 4
gpt4 key购买 nike

我正在尝试实现一种方法,该方法向服务器发送 HTTP 请求并在每两秒内获得响应。我需要向显示响应字符串的富文本框添加一个新行。我使用“Thread.Sleep(2000)”方法来暂停 while 循环。

这是我的代码

private void buttonRequest_Click(object sender, EventArgs e)
{
while (true)
{
using (var client = new WebClient())
{
var response = client.DownloadString("http://localhost:8181/");
var responseString = response;
richTextResponse.Text += responseString + Environment.NewLine;
}
Thread.Sleep(2000);
}
}

但这不能正常工作。它在开始时自行暂停并突然打印相同的字符串超过 5 次。这有什么不对的。我正在本地主机中测试应用程序。因此不存在任何使应用程序变慢的连接问题。

最佳答案

当您在 UI(主)线程上使用 Thread.Sleep(2000) 时,您的应用程序将停止响应任何用户操作 - 它只会挂起 2 秒。这是个坏主意。

我建议你使用Timer此任务的组件。将计时器添加到您的表单(您可以在工具箱中找到它)并设置其 Interval到 2000 毫秒。然后订阅定时器的Tick事件并在此事件处理程序中执行 HTTP 请求。我建议使用异步处理程序来避免在等待响应时挂起:

private async void timer_Tick(object sender, EventArgs e)
{
using (var client = new WebClient())
{
Uri uri = new Uri("http://localhost:8181/");
var response = await client.DownloadStringTaskAsync(uri);
richTextResponse.Text += response + Environment.NewLine;
}
}

当你点击按钮时开始计时:

private void buttonRequest_Click(object sender, EventArgs e)
{
timer.Start();
}

另一种选择是使您的方法异步并使用 Task.Delay而不是让线程休眠(但我可能会使用定时器,这更容易理解和控制):

private async void buttonRequest_Click(object sender, EventArgs e)
{
while (true)
{
using (var client = new WebClient())
{
Uri uri = new Uri("http://localhost:8181/");
var response = await client.DownloadStringTaskAsync(uri);
richTextResponse.Text += response + Environment.NewLine;
}

await Task.Delay(2000);
}
}

关于c# - sleep 线程无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23513566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com