Proper way to Dispose of a BackGroundWorker

后端 未结 5 1740
既然无缘
既然无缘 2020-11-28 11:44

Would this be a proper way to dispose of a BackGroundWorker? I\'m not sure if it is necesary to remove the events before calling .Dispose(). Also is calling .Dispose() ins

5条回答
  •  無奈伤痛
    2020-11-28 12:25

    If it's on a "WinForms" Form let the container take care of it (see the generated Dispose code in the Form.Designer.xyz file)

    In practice I have found that you may need to create an instance of the container and add the worker (or other companent) to it, if anyone knows a more official way to do this yell out!!

    PK :-)

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
            // watch the disposed event....
            backgroundWorker1.Disposed += new EventHandler(backgroundWorker1_Disposed);
    
            // try with and without the following lines
            components = new Container();
            components.Add(backgroundWorker1);
        }
    
        void backgroundWorker1_Disposed(object sender, EventArgs e)
        {
            Debug.WriteLine("backgroundWorker1_Disposed");
        }
    
    //... from the Designer.xyz file ...
    
        /// 
        /// Clean up any resources being used.
        /// 
        /// true if managed resources should be disposed; otherwise, false.
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
    
    }
    

提交回复
热议问题