注意:_这个问题确实与_有关调用异步方法不设置成员变量最初,我有一个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 callMessageBox.Show(taskAssignedToUserId); // updated value
1 回答

largeQ
TA贡献2039条经验 获得超8个赞
你应该像这样修改你的代码:
public async static Task<int> PostRequestUserId(string url, string api_key, string device_token, string device_type, string username)
{
//your code
return id; //insted of setting class variable
}
并在其他一些方法中的其他类中:
var newId = await MyStaticClass.PostRequestUserId(input_values...);
MessageBox.Show(newId);
- 1 回答
- 0 关注
- 183 浏览
添加回答
举报
0/150
提交
取消