gpt4 book ai didi

C# 异步方法仍然挂起 UI

转载 作者:太空狗 更新时间:2023-10-29 17:34:29 28 4
gpt4 key购买 nike

我有这两种方法,我想异步运行以保持 UI 响应。但是,它仍然卡在 UI 上。有什么建议吗?

async void DoScrape()
{
var feed = new Feed();

var results = await feed.GetList();
foreach (var itemObject in results)
{
var item = new ListViewItem(itemObject.Title);
item.SubItems.Add(itemObject.Link);
item.SubItems.Add(itemObject.Description);
LstResults.Items.Add(item);
}
}


public class Feed
{
async public Task<List<ItemObject>> GetList()
{
var client = new WebClient();
string content = await client.DownloadStringTaskAsync(new Uri("anyUrl"));
var lstItemObjects = new List<ItemObject>();
var feed = new XmlDocument();
feed.LoadXml(content);
var nodes = feed.GetElementsByTagName("item");

foreach (XmlNode node in nodes)
{
var tmpItemObject = new ItemObject();
var title = node["title"];
if (title != null) tmpItemObject.Title = title.InnerText;
var link = node["link"];
if (link != null) tmpItemObject.Link = link.InnerText;
var description = node["description"];
if (description != null) tmpItemObject.Description = description.InnerText;
lstItemObjects.Add(tmpItemObject);
}
return lstItemObjects;
}
}

最佳答案

我怀疑 DownloadStringTaskAsync 依赖于 HttpWebRequest.BeginGetResponse在较低的水平。在这种情况下,众所周知 webrequest 的设置不是完全异步的。恼人的(坦率地说,愚蠢的)异步 WebRequest 的 DNS 查找阶段是同步执行的,因此会阻塞。我怀疑这可能是您正在观察的问题。

下面转载的是文档中的警告:

The BeginGetResponse method requires some synchronous setup tasks to complete (DNS resolution, proxy detection, and TCP socket connection, for example) before this method becomes asynchronous. As a result, this method should never be called on a user interface (UI) thread because it might take some time, typically several seconds. In some environments where the webproxy scripts are not configured properly, this can take 60 seconds or more. The default value for the downloadTime attribute on the config file element is one minute which accounts for most of the potential time delay.

你有两个选择:

  1. 从工作线程启动请求(并且在高负载下,由于阻塞行为而面临 ThreadPool 饥饿的风险)
  2. (勉强地)在触发请求之前执行程序化 DNS 查找。这可以异步完成。希望请求随后会使用缓存的 DNS 查找。

我们选择了第三个(也是昂贵的)选项来实现我们自己的适当异步 HTTP 库以获得不错的吞吐量,但在您的情况下它可能有点极端;)

关于C# 异步方法仍然挂起 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6726131/

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