Monday, January 15, 2018

How do I update string value from inside a thread

Leave a Comment

I am coding a Xamarin.Forms cross platform app which works with users accounts. The problem is I get their username from my Database but it doesn't ever update the value of public static string username = "";

I am assuming it is because it's being ran inside a Thread or something to do with the WebRequest, I have done research for quiet a while but haven't been able to find a solution.

The method I am using to update their username is as follows

private void loadUserData()     {         username = "Test";         Uri uri = new Uri("http://example.com/session-data.php?session_id=" + session);         WebRequest request = WebRequest.Create(uri);         request.BeginGetResponse((result) =>         {             try             {                 Stream stream = request.EndGetResponse(result).GetResponseStream();                 StreamReader reader = new StreamReader(stream);                 Device.BeginInvokeOnMainThread(() =>                 {                     string page_result = reader.ReadToEnd();                     var jsonReader = new JsonTextReader(new StringReader(page_result))                     {                         SupportMultipleContent = true // This is important!                     };                     var jsonSerializer = new JsonSerializer();                     try                     {                         while (jsonReader.Read())                         {                             UserData userData = jsonSerializer.Deserialize<UserData>(jsonReader);                             username = userData.username;                         }                      }                     catch (Newtonsoft.Json.JsonReaderException readerExp)                     {                         string rEx = readerExp.Message;                         Debug.WriteLine(rEx);                     }                 });             }             catch (Exception exc)             {                 string ex = exc.Message;                 Debug.WriteLine(ex);             }          }, null);     } 

When the url is opened it prints out the following line

{"id":7,"username":"TestUser","name":"Test User","bio":"Hello World","private":0}

UserData contains the following code

class UserData {     [JsonProperty("id")]     public int id { get; set; }      [JsonProperty("username")]     public string username { get; set; }      [JsonProperty("name")]     public string name { get; set; }      [JsonProperty("bio")]     public string bio { get; set; }      [JsonProperty("private")]     public int isPrivate { get; set; } } 

I also noticed the following error prints out, I tried googling around and haven't found any solutions I understand to fix this

Error parsing positive infinity value. Path '', line 0, position 0.

2 Answers

Answers 1

The error you are getting is a JSON.net one and happens during JSON deserialization, which means there is no problem with updating of the static variable, because the code never gets to that point (it ends on the catch (Newtonsoft.Json.JsonReaderException readerExp)).

This narrows your problem pretty well. There is very likely something wrong with the response you are receiving from the server. Put a breakpoint on the line var jsonReader = ... and check the contents of the page_result variable to see if they don't contain any unexpected characters. Potentially you can also dump the response into a JSON validator to confirm if it is actually valid (https://jsonlint.com/)

Answers 2

Each variable is scoped in a memory dedicated only for the thread where its declaration is performed in, so, when you're accessing that variable from another thread, you're reading a copy of that in the memory of your other thread.
This copy is performed when the thread is synchronized with the another, and not always this is done just when you set the variable.
Therefore, you have to add volatile modifier to your variable declaration, which signs that the variable must be allocated and deallocated in a global synchronization scope.
Try declaring your variable such as this:

public static volatile string username = ""; 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment