我更新了 HttpClient 异步方法中的值,但它没有,如何使用 c#?

注意:_这个问题确实与_有关


调用异步方法不设置成员变量


最初,我有一个taskAssignedToUserId=1,之后我在HttpClient Async Method中更新taskAssignedToUserId但是当我退出方法时,我没有得到 taskAssignedToUserId 的更新值。


代码


string taskAssignedToUserId="1";//default value  

public async static void PostRequestUserId(string url, string api_key, string device_token, string device_type, string username)

{  

    IEnumerable<KeyValuePair<string, string>> queries = new List<KeyValuePair<string, string>>()

    {  

        new KeyValuePair<string, string>("username",username),  

        new KeyValuePair<string, string>("api_key",api_key),  

        new KeyValuePair<string, string>("device_token",device_token),  

        new KeyValuePair<string, string>("device_type",device_type)  

    };  

    HttpContent q = new FormUrlEncodedContent(queries);  

    using (HttpClient client = new HttpClient())

    {  

        using (HttpResponseMessage response = await client.PostAsync(url, q))

        {  

            using (HttpContent content = response.Content)

            {  

                var mycontent = await content.ReadAsStringAsync();  

                var jo = JObject.Parse(mycontent);  

                string validApi = jo["Result"]["valid_api"].ToString();  

                try  

                {  

                    if (validApi == "True")  

                    {  

                        taskAssignedToUserId = jo["Result"]["user_id"].ToString();  

                    }  

                    else  

                    {  

                        MessageBox.Show("API is invalid!");  

                    }  

                }  

                catch (Exception ex)  

                {  

                    MessageBox.Show(ex.Message);  

                }  

            }  

        }  

    }  

}  


//function call

MessageBox.Show(taskAssignedToUserId); // updated value  


眼眸繁星
浏览 185回答 1
1回答

largeQ

你应该像这样修改你的代码:public async static Task<int> PostRequestUserId(string url, string api_key, string device_token, string device_type, string username){&nbsp; &nbsp; //your code&nbsp; &nbsp; return id; //insted of setting class variable}并在其他一些方法中的其他类中:var newId = await MyStaticClass.PostRequestUserId(input_values...);MessageBox.Show(newId);
打开App,查看更多内容
随时随地看视频慕课网APP