WeatherInformation WP8: global data LOCK
authorgu.martinm@gmail.com <gu.martinm@gmail.com>
Sat, 16 Aug 2014 07:48:13 +0000 (09:48 +0200)
committergu.martinm@gmail.com <gu.martinm@gmail.com>
Sat, 16 Aug 2014 07:48:13 +0000 (09:48 +0200)
Setting/getting global data from different thread. Requires lock
statement.

WindowsPhone/WeatherInformation/WeatherInformation/App.xaml.cs
WindowsPhone/WeatherInformation/WeatherInformation/MainPage.xaml.cs

index b10cfec..c4897c3 100644 (file)
@@ -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;
+                    }
                 }
             }
         }
index 3c83762..428b1f2 100644 (file)
@@ -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);