简体   繁体   中英

Insert Items in list view without blocking UI Thread in c#

I have two threads that access the UI thread to do some operations, first thread just show a loading image, and the second thread populates a listview with a some itens.

My problem is when the listview is being populated it blocks the UI thread and the loading image stops.

Thread th = new Thread(new ThreadStart(PopulateListView));
th.Start();

void PopulateListView()
    {
        for (int i = 0; i < 4000; i++)
        {
            Invoke((MethodInvoker)(() => ultraListView1.Items.Add("abc"+i)));
        }
    }

What i'm doing wrong ??

What i'm doing wrong ??

You can only populate the UI from the main thread. As soon as you do Invoke , you're pushing the work back onto the main (UI) thread. This means that you will still block the UI, even if you start this from a separate thread.

There is no direct way around this. If your data takes a long time to load, you can potentially load it on a background thread, but adding it to the ListView will always need to be done on the UI thread.

Bit of a rush, so sorry if I'm whiffing this one.

  1. Generate a worker thread to to perform the async operation. (which it looks like you've got handled.) The Backgroundworker class may also be helpful. It has built in worker thread cancellation, and ProgressChanged event.

  2. Every time a new chunk of data becomes available (a single entry, or if you'd prefer, a set of entries) raise an event passing the new data along.

  3. In the event handler for the "announcement", push yourself to the GUI thread and add it to the control's data source.

This article has a nice explanation on checking your current thread, and invoking the GUI thread where necessary:

http://kristofverbiest.blogspot.com/2007/02/simple-pattern-to-invoke-gui-from.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM