Dips
Dips

Reputation: 228

Dispose function of user control not calling from BeginInvoke Method in c# winforms

I have one Main Form and on this Main Form I am adding one user control like below.

objCustomer = new Customer();
objCustomer.Top = this.Top;
objCustomer.Left = this.Left;
this.BeginInvoke((MethodInvoker)delegate { this.Controls.Add(objCustomer); });

Now, on some event I have to unload this control and load other control.

if (objCustomer != null)
{
this.Invoke((MethodInvoker)delegate { this.Controls.Remove(objCustomer); });
this.Invoke((MethodInvoker)delegate { objCustomer.Dispose(); });
}
objEmployee = new Employee();
objEmployee.Top = this.Top;
objEmployee.Left = this.Left;

this.BeginInvoke((MethodInvoker)delegate { this.Controls.Add(objEmployee); });

Now, on Customer Dispose function I have some routine are calling for logoff from other system.

protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            Common.Log.LogEvent("Customer", "DisposedCall");
            LogOffServer();

            components.Dispose();

        }
        base.Dispose(disposing);
    }

I believe this Dispose event is not calling.

Please help me.

Thank you

Upvotes: 0

Views: 524

Answers (1)

jeuton
jeuton

Reputation: 543

Assuming that last Dispose() method is for your Form, if your conditional block is not being executed it is because all controls on a Winform are disposed before the Form's Dispose() method is called. This means that components != null is false (because all components are already disposed) and the condition evaluates to false.

Winform Event Lifecycle

Upvotes: 1

Related Questions