HttpClient SendAsync可以不阻止GUI线程吗? [英] Can HttpClient SendAsync not block GUI thread?

查看:57
本文介绍了HttpClient SendAsync可以不阻止GUI线程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Windows Forms GUI线程现在停滞一秒钟,然后在异步 HttpClient SendAsync 期间停滞.除此之外,一切正常(我得到了数据).我想向不同的服务器发出频繁且希望并行的请求,以经常更新屏幕.我正在尝试启动多个请求,这些请求将响应发布到以后由GUI线程处理.下面的代码是我的代码的简化.我检查了 SendAsync 之前和之后的时间,发现在GUI窗口冻结(无法移动,滚动等)并且轮询计时器处于非活动状态(有时不超过2秒)的情况下(计数器永不递增.)

The Windows Forms GUI thread keeps stalling for a second now and then during async HttpClient SendAsync. Except for that, everything works fine (I get data). I want to do frequent and hopefully parallel requests to different servers to update the screen frequently. I am trying to launch multiple requests that post the responses for processing by the GUI thread later. The code below is a simplification of my code. I've checked the time before and after SendAsync and see it is sometimes up to 2 seconds while the GUI window is frozen (can't be moved, scrolled, etc) and the polling timer is inactive (counter never incremented).

使用异步 Task DoWork 无效.

class Worker
{
    HttpClient client = new HttpClient();
    bool busy = false;
    string data = "";
    //public async Task DoWork()
    public async void DoWork()
    {
        if ( busy ) return;
        busy = true;
        HttpRequestMessage request = new HttpRequestMessage(method, requestUrl);
        HttpResponseMessage response = await client.SendAsync( request );
        data = ... from response ...
        busy = false;
    }
}
int counter;
private void Update(object sender, EventArgs e)
{
    ++counter;
    foreach ( Worker worker in workers )
        worker.DoWork();
}
...
List<Worker> workers = ...
var poll = new System.Windows.Forms.Timer();
poll.Tick += Update;
poll.Interval = 250;
poll.Enabled = true;
...

推荐答案

SendAsync 是足够异步的(即使它内部使用线程).UI本身的更新确实很慢,并且导致UI冻结.

SendAsync is sufficiently asynchronous (even if it uses threads internally). Updating UI itself is really slow and the cause of UI freezing.

这篇关于HttpClient SendAsync可以不阻止GUI线程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆