Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Background Worker UI Update

I am trying to use a background worker in order to retrieve a large amount of data from the database without stalling the main thread. This seems to work well, except that when it comes to update the UI, the update freezes the screen. Relevant code as follows:

    private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {               
        lvwTest.BeginUpdate();
        lvwTest.Items.Clear();

        // Populate the UI
        foreach (TestItem ti in testData)
        {
            ListViewItem lvi = lvwTest.Items.Add(ti.Value1);
            lvi.SubItems.Add(ti.Value2);
        }

        lvwTest.EndUpdate();                     
    }

The update takes around 2 - 3 seconds, for which time the screen is locked. I realise that only the main thread can update the screen, but is it possible to load this data into memory in some way (in a background thread or another instance of a listview or something) and then just display it? All I want to happen is for the program to simply refresh the data without taking up time in the main thread.

like image 264
Paul Michaels Avatar asked Nov 05 '22 10:11

Paul Michaels


1 Answers

I recommend loading the data into memory and using a virtual mode ListView. That way, you only create the ListViewItem objects as they are needed.

like image 88
Stephen Cleary Avatar answered Nov 12 '22 20:11

Stephen Cleary