Populating a listview from another thread

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

    A simple search here on SO would have brought up many results that tell you that it is not allowed to change a GUI control from a thread other than the thread which created the control (cross-thread GUI access).

    To do so, everything related to updating the ListView must be done using this.Invoke or this.Dispatcher.Invoke (in WPF).

    EDIT
    For example this thread here.

    Sample code:

    private delegate void MyDelegate(string s);
    
    public void UpdateControl(Control targetControl, string text)
    {
        if (targetControl.InvokeRequired)
        {
            // THIS IS STILL THE IN THE CONTEXT OF THE THREAD
            MyDelegate call = new MyDelegate(UpdateControl);
            targetControl.Invoke(call, new object[] { text });
        }
        else
        {
            // do control stuff
            // THIS IS IN THE CONTEXT OF THE UI THREAD
        }
    }
    

提交回复
热议问题