为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
眼眸繁星 2022-01-15 19:24:02
注意:_这个问题确实与_有关调用异步方法不设置成员变量最初,我有一个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);


查看完整回答
反对 回复 2022-01-15
  • 1 回答
  • 0 关注
  • 183 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号