Invoke or BeginInvoke cannot be called on a control until the window handle has been created

流过昼夜 提交于 2019-12-08 13:02:03

问题


hey guys I get this exception when my application closes. CustomerReadySub is an event that I have subscribed to.

The error happens on this line

fTypeLabel.Invoke(new MethodInvoker(fuelTypeChosen));

public void CustomerReadySub(object sender, CustomerReadyEventArgs fuel)
    {
            // code to handle the event
            string CustReady = null;

            //checks what fuel is chosen and then activates the pump
            fuelType = fuel.SelectedFuel.ToString();

            if (!String.IsNullOrEmpty(fuelType))
            {
                fTypeLabel.Invoke(new MethodInvoker(fuelTypeChosen));

                if (fuelType == "Unleaded") //checks fuel type and displays price accordingly
                {
                    pplText.Invoke(new MethodInvoker(petrol));
                }
                else
                {
                    pplText.Invoke(new MethodInvoker(diesel));
                }

                CustReady = "READY";
                WCFPump.sendReady(CustReady);
            }

            while (WCFPump.getOK() == 0) { /*do nothing*/} //used to loop around until OK is retrieved
            if (pumpID == WCFPump.getOK())
            {
                CustGen.ActivatePump();
            }

    }

    private void fuelTypeChosen()
    {
        fTypeLabel.Text = fuelType;
    }

I am not really sure what is causing the problem.


回答1:


The error seems quite clear, except for the 'until' part when you are already closing down. I think you can also read it as "Invoke or BeginInvoke cannot be called on a control after the window handle has been destroyed"

So your event fires after the Window has been destroyed. The actual code responsible for that is not posted but the code we do see is really happy to do busy-waiting. So apparently you are disturbing the Windows event mechanism enough to cause this timing problem.

Short fix:

      if (! fTypeLabel.IsHandleCreated) return;  // emergency exit
      fTypeLabel.Invoke(new MethodInvoker(fuelTypeChosen));

but you should really consider fixing the synchronous nature of your code. Uses events and async.



来源:https://stackoverflow.com/questions/16398395/invoke-or-begininvoke-cannot-be-called-on-a-control-until-the-window-handle-has

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!