From fc8c2704522ccc16596982ac8aa29dcd60c8ae16 Mon Sep 17 00:00:00 2001 From: "gu.martinm@gmail.com" Date: Sat, 16 Aug 2014 09:48:13 +0200 Subject: [PATCH] WeatherInformation WP8: global data LOCK Setting/getting global data from different thread. Requires lock statement. --- .../WeatherInformation/WeatherInformation/App.xaml.cs | 16 +++++++++++++--- .../WeatherInformation/MainPage.xaml.cs | 2 -- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/WindowsPhone/WeatherInformation/WeatherInformation/App.xaml.cs b/WindowsPhone/WeatherInformation/WeatherInformation/App.xaml.cs index b10cfec..c4897c3 100644 --- a/WindowsPhone/WeatherInformation/WeatherInformation/App.xaml.cs +++ b/WindowsPhone/WeatherInformation/WeatherInformation/App.xaml.cs @@ -31,15 +31,25 @@ namespace WeatherInformation // Declare a private variable to store application state. private WeatherData _remoteWeatherData; + private readonly Object _lock = new Object(); // Declare a public property to access the application data variable. public WeatherData ApplicationDataObject { - get { return _remoteWeatherData; } + get + { + lock (_lock) + { + return _remoteWeatherData; + } + } set { - if (value != _remoteWeatherData) + lock (_lock) { - _remoteWeatherData = value; + if (value != _remoteWeatherData) + { + _remoteWeatherData = value; + } } } } diff --git a/WindowsPhone/WeatherInformation/WeatherInformation/MainPage.xaml.cs b/WindowsPhone/WeatherInformation/WeatherInformation/MainPage.xaml.cs index 3c83762..428b1f2 100644 --- a/WindowsPhone/WeatherInformation/WeatherInformation/MainPage.xaml.cs +++ b/WindowsPhone/WeatherInformation/WeatherInformation/MainPage.xaml.cs @@ -74,14 +74,12 @@ namespace WeatherInformation // If the application member variable is not empty, // set the page's data object from the application member variable. - // TODO: I am setting and getting ApplicationDataObject from different threads!!!! What if I do not see its last value? Do I need synchronization? :/ WeatherData weatherData = (Application.Current as WeatherInformation.App).ApplicationDataObject; if (!IsDataFresh(locationItem.LastRemoteDataUpdate) || weatherData == null) { // Load remote data (aynchronous way by means of async/await) // Gets the data from the web. - // TODO: multiple threads writing/reading same data :( (Application.Current as WeatherInformation.App).ApplicationDataObject = await GetRemoteDataAsync(locationItem).ConfigureAwait(false); -- 2.1.4