Avoid calling Invoke when the control is disposed

后端 未结 14 1343
花落未央
花落未央 2020-12-01 16:09

I have the following code in my worker thread (ImageListView below is derived from Control):

if (mImageListView != null &&          


        
相关标签:
14条回答
  • 2020-12-01 16:39

    Try using

    if(!myControl.Disposing)
        ; // invoke here
    

    I had the exact same problem as you. Ever since I switched to checking .Disposing on the control, the ObjectDisposedException has gone away. Not saying this will fix it 100% of the time, just 99% ;) There is still a chance of a race condition between the check to Disposing and the call to invoke, but in the testing I've done I haven't ran into it (I use the ThreadPool and a worker thread).

    Here's what I use before each call to invoke:

        private bool IsControlValid(Control myControl)
        {
            if (myControl == null) return false;
            if (myControl.IsDisposed) return false;
            if (myControl.Disposing) return false;
            if (!myControl.IsHandleCreated) return false;
            if (AbortThread) return false; // the signal to the thread to stop processing
            return true;
        }
    
    0 讨论(0)
  • 2020-12-01 16:41

    This works for me

    if (this.IsHandleCreated){
        Task.Delay(500).ContinueWith(_ =>{
            this.Invoke(fm2);
        });
    } else {
      this.Refresh();
    }
    
    0 讨论(0)
提交回复
热议问题