C# async methods still hang UI

后端 未结 3 1587
独厮守ぢ
独厮守ぢ 2020-12-10 05:59

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()
            


        
3条回答
  •  清歌不尽
    2020-12-10 06:05

    How many items are you adding into your list view?

    Unless you take action to prevent it, the WinForms list view will do a lot of processing every time you add an item into the list. This can take so long that adding just 100 items can take several seconds.

    Try using BeginUpdate and EndUpdate around your loop to defer the bookkeeping of ListView until you're finished.

    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();
        }
    }
    

    Got to use a try finally to avoid all sorts of pain if there's an exception.

提交回复
热议问题