C# ForecastIOPortable lib in WPF application with Timer -
i'm trying weather information using forecastioportable library. have method works without problems in console application, same in wpf application.
forecastapi api = new forecastapi("xxxx"); var forecast = api.getweatherdataasync(xxxx, xxxx); var results = forecast.result; int tempc = (int)(5.0 / 9.0 * (results.currently.temperature - 32));
problem shows when try call method tick of timer, program freezes , vs doesn't show information exception. when checked breakpoints, information results doesn't change , time has value=null. reason of problem , how deal it?
you using async process you getting task rather result.
in console app have .wait() task resolve before result populated. better test using wpf application can await getweatherdataasync method.
probably best way handle wrap timer in class , pass in various bits.
you can try this
public class forecastapiasynctimer : idisposable { private forecastapi _api; private timer _timer; public forecastapiasynctimer(timer timer, forecastapi forecastapi) { if (timer == null) throw new argumentnullexception("timer"); if (forecastapi == null) throw new argumentnullexception("forecastapi"); _api = forecastapi; _timer = timer; _timer.elapsed += _timer_elapsed; } public forecastapiasynctimer(double interval, forecastapi forecastapi) { if (forecastapi == null) throw new argumentnullexception("forecastapi"); _api = forecastapi; _timer = new timer(interval); _timer.elapsed += _timer_elapsed; } public void start() { _timer.start(); } public void stop() { _timer.stop(); } protected async virtual task<int> timerelapsedtask() { var forecast = await _api.getweatherdataasync(40.7505045d, -73.9934387d); int tempc = (int)(5.0 / 9.0 * (forecast.currently.temperature - 32)); return tempc; } async void _timer_elapsed(object sender, elapsedeventargs e) { int result = await timerelapsedtask(); // result. } ~forecastapiasynctimer() { dispose(false); } public void dispose() { dispose(true); gc.suppressfinalize(this); } protected virtual void dispose(bool disposing) { if (!disposing || _timer == null) return; _timer.dispose(); _timer = null; } }
example usage 1.
static void main(string[] args) { string apikey = "yourapikey"; forecastapi api = new forecastapi(apikey); using (var forecasttimer = new forecastapiasynctimer(5000, api)) { forecasttimer.start(); while (!console.keyavailable) { } } }
example usage 2:
static void main(string[] args) { string apikey = "yourapikey"; forecastapi api = new forecastapi(apikey); timer timer = new timer(5000); var forecasttimer = new forecastapiasynctimer(timer, api); forecasttimer.start(); while (!console.keyavailable) { } }
Comments
Post a Comment