【发布时间】:2021-03-07 05:39:33
【问题描述】:
所以我正在用我的代码监听服务器端事件,只是将它写在控制台上(现在),但这似乎使我的窗口表单 UI 冻结
有问题的代码(我从主窗体的函数中调用)
static async Task hello()
{
HttpClient client = new HttpClient();
//client.Timeout = TimeSpan.FromSeconds(5);
while (true)
{
try
{
Console.WriteLine("Establishing connection");
using (var streamReader = new StreamReader(await client.GetStreamAsync(url)))
{
while (!streamReader.EndOfStream)
{
var message = await streamReader.ReadLineAsync();
Console.WriteLine(message.ToString());
}
}
}
catch (Exception ex)
{
//Here you can check for
//specific types of errors before continuing
//Since this is a simple example, i'm always going to retry
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine("Retrying in 5 seconds");
await Task.Delay(TimeSpan.FromSeconds(5));
}
}
}
提前致谢
【问题讨论】:
-
我的大部分代码来自本教程makolyte.com/…
-
当你到达 EndOfStream 时,你应该退出外部的 while 循环。