Avoid calling Invoke when the control is disposed

后端 未结 14 1448
花落未央
花落未央 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:29

    The solution proposed by Isak Savo

    try
      {
      myForm.Invoke(myForm.myDelegate, new Object[] { message });
      }
    catch (ObjectDisposedException)
      { //catch exception if the owner window is already closed
      }
    

    works in C# 4.0 but for some reasons it fails in C#3.0 (the exception is raised anyway)

    So I used another solution based on a flag indicating if the form is closing and consequently preventing the use of invoke if the flag is set

       public partial class Form1 : Form
       {
        bool _closing;
        public bool closing { get { return _closing; } }
    
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            _closing = true;
        }
    
     ...
    
     // part executing in another thread: 
    
     if (_owner.closing == false)
      { // the invoke is skipped if the form is closing
      myForm.Invoke(myForm.myDelegate, new Object[] { message });
      }
    

    This has the advantage of completely avoiding the use of try/catch.

提交回复
热议问题