Populating a listview from another thread

后端 未结 5 676
旧时难觅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:32

    Usually I'm doing it like this:

    using System;
    using System.Windows.Forms;
    
    namespace TestWinFormsThreding
    {
        class TestFormControlHelper
        {
            delegate void UniversalVoidDelegate();
    
            /// 
            /// Call form control action from different thread
            /// 
            public static void ControlInvoke(Control control, Action function)
            {
                if (control.IsDisposed || control.Disposing)
                    return;
    
                if (control.InvokeRequired)
                {
                    control.Invoke(new UniversalVoidDelegate(() => ControlInvoke(control, function)));
                    return;
                }
                function();
            }
        }
    
        public partial class TestMainForm : Form
        {
        // ...
        // This will be called from thread not the same as MainForm thread
        private void TestFunction()
        {
            TestFormCotrolHelper.ControlInvoke(listView1, () => listView1.Items.Add("Test"));
        }   
        //...
        }
    }
    

提交回复
热议问题