How do I update string value from inside a thread How do I update string value from inside a thread json json

How do I update string value from inside a thread


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/)


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 = "";