Populating a listview from another thread

后端 未结 5 646
旧时难觅i
旧时难觅i 2021-01-21 21:01

I\'m trying to populate a listview from another class, but I\'m geting this error: \" Cross-thread operation not valid: Control \'listView1\' accessed from a thread other than t

5条回答
  •  时光取名叫无心
    2021-01-21 21:30

    A neat trick to avoid duplicate code or malfunction when a function is called both from UI thread and other threads is:

    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
    
            void AddItems( string[] items )
            {
                if(InvokeRequired)
                {
                    Invoke((MethodInvoker) delegate { this.AddItems(items); });
                    return;
                }
                ListViewItem[] range = (items.Select(item => new ListViewItem(item))).ToArray();
                listView1.Items.AddRange(range);
            }
        }
    }
    

    The first time the function enters in another thread, invoke is called and the function simply calls itself again, this time in the right thread context. The actual work is then written down only once after the if() block.

提交回复
热议问题