在创建窗口句柄之前,无法在控件上调用Invoke或BeginInvoke

Dor*_*tuh 0 c# wcf invoke

嘿伙计们,当我的申请结束时,我得到了这个例外.CustomerReadySub是我订阅的活动.

错误发生在这一行

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;
    }
Run Code Online (Sandbox Code Playgroud)

我不确定是什么导致了这个问题.

Hen*_*man 5

错误似乎很清楚,除了你已经关闭的'until'部分.我认为您也可以将其读作" 在窗口句柄被销毁无法在控件上调用Invoke或BeginInvoke "

因此,在Window被销毁后,您的事件将会触发.负责这个的实际代码没有发布,但我们看到的代码真的很乐意做忙等待.所以显然你打扰Windows事件机制足以导致这个时间问题.

简短修复:

      if (! fTypeLabel.IsHandleCreated) return;  // emergency exit
      fTypeLabel.Invoke(new MethodInvoker(fuelTypeChosen));
Run Code Online (Sandbox Code Playgroud)

但你应该考虑修复代码的同步性.使用事件和异步.