0

I basically have a method that is checking a service constantly in a different thread. This works fine, but I need to make a check so that if the host closes, it keeps trying until service is resumed.

I thought this would work

private void GetTankLevels()
        {
            Service1Client client = new Service1Client();
            while (true)
            {
                try
                {
                    this.DieselBox.Invoke(new MethodInvoker(delegate { DieselBox.Text = client.GetTankAmounts("Diesel").ToString(); }));
                    this.PetrolBox.Invoke(new MethodInvoker(delegate { PetrolBox.Text = client.GetTankAmounts("Unleaded").ToString(); }));
                    double DFuelLvl = client.GetTankAmounts("Diesel");
                    double PFuelLvl = client.GetTankAmounts("Unleaded");

                    int DieselProgress = (int)DFuelLvl;
                    int petrolProgress = (int)PFuelLvl;
                    if (DFuelLvl < 300)
                    {

                        this.DieselBar.Invoke(new MethodInvoker(delegate { DieselBar.Value = DieselProgress; }));

                    }
                    else if (DFuelLvl > 300 && DFuelLvl < 500)
                    {
                        this.DieselBar.Invoke(new MethodInvoker(delegate { DieselBar.Value = DieselProgress; }));

                    }
                    else if (DFuelLvl > 500 && DFuelLvl < 850)
                    {
                        this.DieselBar.Invoke(new MethodInvoker(delegate { DieselBar.Value = DieselProgress; }));

                    }
                    else
                    {
                        this.DieselBar.Invoke(new MethodInvoker(delegate { DieselBar.Value = DieselProgress; }));

                    }

                    if (PFuelLvl < 300)
                    {
                        this.Petrolbar.Invoke(new MethodInvoker(delegate { Petrolbar.Value = petrolProgress; }));

                    }
                    else if (PFuelLvl > 300 && PFuelLvl < 500)
                    {
                        this.Petrolbar.Invoke(new MethodInvoker(delegate { Petrolbar.Value = petrolProgress; }));

                    }
                    else if (PFuelLvl > 500 && PFuelLvl < 850)
                    {
                        this.Petrolbar.Invoke(new MethodInvoker(delegate { Petrolbar.Value = petrolProgress; }));

                    }
                    else
                    {
                        this.Petrolbar.Invoke(new MethodInvoker(delegate { Petrolbar.Value = petrolProgress; }));

                    }
                }
                catch
                {
                    MessageBox.Show("Lost connection to the host... Please wait");

                }

            }
        }

But it's being a bit unpredictable. Ideas?

4

1 回答 1

2

您正在从 访问您的服务Invoke(),因此代码不是在您的线程上执行,而是在主 UI 线程上执行。当那里抛出异常时,它不会被您的 try/catch 块捕获。

您可以将所有服务调用移到 Invoke 之外,以便它们在您的线程上执行。

于 2013-04-10T15:24:47.220 回答