【问题标题】:client.GetStreamAsync(url) is freezing my UIclient.GetStreamAsync(url) 正在冻结我的 UI
【发布时间】: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 循环。

标签: c# wpf


【解决方案1】:

我已经解决了这个问题,似乎 async/await 任务冻结了 GUI。要阻止这种情况发生,您需要使用 Task.Run(() => your_function());当你调用一个异步函数时

此问题可能与以下内容重复:GUI freezes when using async/await ...因此,如果您想了解有关该主题的更多知识,请前往那里

【讨论】:

    猜你喜欢
    • 2010-09-21
    • 2021-01-28
    • 2013-01-20
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2022-01-25
    相关资源
    最近更新 更多