从多个线程添加到ListView非常快

时间:2012-10-11 16:16:12

标签: c# listview

在向ListView添加项目时,我使用以下方法。

我已确保ListView双缓冲,并尝试优化我能想到的所有内容 - 但无论我做什么,在快速添加项目时UI都很缓慢。

我已经有这个问题已经有一段时间了,并试图找到一个解决方案,但每次放弃,因为我只是无法解决它。这次我希望能解决这个问题。 :)

我可能会考虑一些自定义解决方案吗?有没有可以处理“SPEED”的好的?或者我目前的代码能做些什么吗?

方法:

private void AddNewItemToListView(string gPR, string rank, string category, string name, string url, string email, string address, string phone, string metadesc, string metakeywords, string mobile, string numbofreviews, string rating, string facebook, string twitter, string googleplus, string linkedin, string sitemap, string siteage, string backlinks, string trafficvalue)
{
    Invoke(new MethodInvoker(
        delegate
            {
                string[] row1 = { url, urlSec, address, phone, metadesc, metakeywords, mob, REV, RT, gPR, FB, TW, googleplus, LI, ST, SA, BL, TV };
                ListViewItem item = new ListViewItem();

                flatListView1.Items.Add(name).SubItems.AddRange(row1);                               
            }
        ));
}

2 个答案:

答案 0 :(得分:2)

您可以添加到缓慢消耗的列表中,而不是直接添加到UI,而是每秒在x项目中添加到UI。我在下面快速写了一个松散的例子,但你可以在这里阅读更多:http://msdn.microsoft.com/en-us/library/dd267312.aspx

private BlockingCollection queue;

public void Start() 
{
    queue = new BlockingCollection<string[]>();
    Task.Factory.StartNew(() => { 
        while(!queue.IsCompleted) 
        { 
            var item = queue.Take(); 
            //add to listview and control speed 
        } 
    });

    Start.Whatever.Produces.Items();
    //when all items added to queue.
    queue.CompleteAdded();

}

private void AddnewItemToListView(...) 
{
    var row = ...;
    queue.Add(row);
}

答案 1 :(得分:2)

您是否可以在工作开始时使用ListView.SuspendLayout()方法,然后在结束时调用ListView.ResumeLayout()?我想,这会加速很多事情。您也可以尝试定期恢复以获得一些反馈。例如,通过在指定的位置插入以下代码:

// Start of work
flatListView1.SuspendLayout();

// Below code inside your delegate

flatListView1.Items.Add(name).SubItems.AddRange(row1);   

if ((flatListView1.Items.Count % 1000) == 0)
{
    // Force a refresh of the list
    flatListView1.ResumeLayout();
    // Turn it off again
    flatListView1.SuspendLayout();         
}

// End of code inside delegate

// Resume layout when adding is finished

flatListView1.ResumeLayout();