C# 异步方法仍然挂起 UI
我有这两种方法,我想运行异步以保持 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;
}
}
I have these two methods, that I want to run async to keep the UI responsive. However, it's still hanging the UI. Any suggestions?
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
您似乎将异步与并行混淆了。它们都是基于Tasks,但又完全不同。不要假设async
方法是并行运行的——它们不是并行运行的。
异步默认在同一线程中工作,除非有原因迫使异步引擎启动新线程,例如主线程没有消息泵的情况。但总的来说,我倾向于认为 async 关键字在同一个线程中运行。
您使用 WinForms,因此 UI 线程有一个消息泵。因此,上面的所有代码都在 UI 线程中运行。
您必须明白,您在这里没有引入任何并行性。您通过async
关键字引入的是异步操作,NOT并行。除了对 DownloadStringTaskAsync
的一次调用之外,您没有做任何事情来“让您的 UI 响应”,这不会强迫您等待数据到达,但您仍然必须在 UI 线程中完成所有网络处理(DNS 查找等)——这是正在执行的异步操作(本质上“节省”了等待下载的时间)。
为了保持 UI 的响应能力,您需要将耗时的工作分拆到单独的线程中,同时保持 UI 线程空闲。您没有使用 async
关键字来执行此操作。
您需要使用 Task.Factory.StartNew(...)
显式启动一个新线程来执行后台处理。
您要在列表视图中添加多少项目?
除非您采取措施阻止它,否则每次您向列表中添加项目时,WinForms 列表视图都会执行大量处理。这可能需要很长时间,以至于仅添加 100 个项目就可能需要几秒钟。
尝试在循环中使用 BeginUpdate
和 EndUpdate
来推迟 ListView 的簿记,直到完成为止。
async void DoScrape()
{
var feed = new Feed();
var results = await feed.GetList();
LstResults.BeginUpdate(); // Add this
try
{
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);
}
}
finally
{
LstResults.EndUpdate();
}
}
如果出现异常,必须使用 try finally 来避免各种痛苦。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我怀疑
DownloadStringTaskAsync
依赖于 < code>HttpWebRequest.BeginGetResponse 在较低级别。在这种情况下,我们知道 Web 请求的设置并不是完全异步的。令人烦恼(坦率地说,愚蠢的是)异步 WebRequest 的 DNS 查找阶段是同步执行的,因此会阻塞。我怀疑这可能是您正在观察的问题。下面转载的是文档中的警告:
您有两种选择:
我们选择了第三种(也是昂贵的)选项,即实现我们自己的正确异步 HTTP 库以获得不错的吞吐量,但在您的情况下这可能有点极端;)
I suspect
DownloadStringTaskAsync
relies uponHttpWebRequest.BeginGetResponse
at a lower level. This being the case, it is known that the setup for a webrequest is not fully asynchronous. Annoyingly (and frankly, stupidly) the DNS lookup phase of an asynchronous WebRequest is performed synchronously, and therefore blocks. I suspect this might be the issue you are observing.Reproduced below is a warning in the docs:
You've two choices:
We went for the 3rd (and costly) option of implementing our own properly asynchronous HTTP library to get decent throughput, but it's probably a bit extreme in your case ;)