INotifyPropertyChanged causes cross-thread error

后端 未结 4 1787
走了就别回头了
走了就别回头了 2020-12-16 06:21

Here is my scenarion:

I have a GridControl bound to a BindingList. At first what I was doing was creating a worker thread and access the BindingList directly, but th

4条回答
  •  轮回少年
    2020-12-16 06:29

    Just in case someone has run into the same problem... I managed to fix it after some hours. Here is what I did:

    Basically the problem was that the object implementing INotifyPropertyChanged was living in a worker thread, and this causes problems when accessing the UI thread.

    So what I did was pass a reference to the object that needs to be updated to the INotifyPropertyChanged object, and then use invoke on it.

    Here is what it looks like:

        public event PropertyChangedEventHandler PropertyChanged;
    
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                //If the Proxy object is living in a non-UI thread, use invoke
                if (c != null)
                {
                    c.BeginInvoke(new Action(() => handler(this, new PropertyChangedEventArgs(name))));
                }
                //Otherwise update directly
                else
                {
                    handler(this, new PropertyChangedEventArgs(name));
                }
    
            }
        }
    
        //Use this to reference the object on the UI thread when there is need to
        public Control C
        {
            set { c = value; }
        }
    

    From the thread, all I did was:

                        prox.c = this;
                        //Logic here
                        prox.c = null;
    

    Hope this helps someone!!

提交回复
热议问题