简体   繁体   English

如何从线程内更新字符串值

[英]How do I update string value from inside a thread

I am coding a Xamarin.Forms cross platform app which works with users accounts. 我正在编写一个与用户帐户一起使用的Xamarin.Forms跨平台应用程序。 The problem is I get their username from my Database but it doesn't ever update the value of public static string username = ""; 问题是我从我的数据库中获取了他们的用户名,但它并没有更新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. 我假设它是因为它是在一个线程内运行或与WebRequest有关,我已经做了一段时间的安静研究,但一直无法找到解决方案。

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 当URL打开时,它打印出以下行

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

UserData contains the following code UserData包含以下代码

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. 路径'',第0行,第0位。

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) ). 你得到的错误是一个JSON.net并且在JSON反序列化期间发生,这意味着更新静态变量没有问题,因为代码永远不会到达那一点(它以catch (Newtonsoft.Json.JsonReaderException readerExp)结束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. 在行var jsonReader = ...上放置一个断点,并检查page_result变量的内容,看它们是否包含任何意外字符。 Potentially you can also dump the response into a JSON validator to confirm if it is actually valid ( https://jsonlint.com/ ) 您也可以将响应转储到JSON验证器中以确认它是否实际有效( 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. 因此,您必须将volatile修饰符添加到变量声明中,这表示必须在全局同步范围中分配和取消分配变量。
Try declaring your variable such as this: 尝试声明您的变量,例如:

public static volatile string username = "";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM