Question

I have a problem with the Wunderground forecast that I am using to retrieve data in c# program.

When I click to retrieve data once everything is working correctly but when I hit the button once more I am getting this error: Background Worker

Here is my code:

        private void bweather_DoWork(object sender, DoWorkEventArgs e)
        {
            string lat = Math.Round(deciLat).ToString();
            string lng = Math.Round(deciLon).ToString();
            string latlong = String.Format("{0},{1}", lat.Replace(',', '.'), lng.Replace(',', '.'));

            //Initialize Current as a new Day
            dow.Current = new WeatherLib.WDay();

            //Using Wunderground as the provider we populate the property with current data for the latlong entered into the textbox
            try
            {
                dow = WeatherLib.WProvider.Wunderground(latlong);
                writeToLogFile("Retrieve weather info successfully on: " + latlong);
            }
            catch (Exception ex)
            {
                writeToLogFile(ex.Message);
            }
        }

Here is the refresh button:

 private void weather_refresh_Click(object sender, EventArgs e)
        {
            writeToLogFile("Weather button pressed");
            weather_descripton.Clear();
            weather_speed_textbox.Clear();
            weather_tem_textbox.Clear();
            weather_rain_text.Clear();
            weather_wind_dir_textbox.Clear();
            weather_descripton.AppendText("Searching.......");
            if (!bweather.IsBusy)
            {
                bweather.CancelAsync();
            }
            bweather.RunWorkerAsync();
        }

And here are the event handlers:

// Weather handlers
            bweather.WorkerSupportsCancellation = true;
            bweather.DoWork += bweather_DoWork;
            bweather.RunWorkerCompleted += bweather_RunWorkerCompleted;

Any idea why is this not working as it should?

Thank you

Was it helpful?

Solution

Well the error message suggests that you're trying to use the same background worker more than once.

You're asking it to cancel if it's still busy, but that doesn't mean it'll cancel immediately. As far as I can tell, the BackgroundWorker code isn't even checking whether it's been cancelled, which means cancelling it won't really achieve anything useful.

I would suggest that if it's busy, you should instead just ignore the request. In fact, it might be better to disable the button completely when you start the operation, and only re-enable it when the operation completes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top