Note:_This question does related to _
Calling async method does not set member variable
Initially, I have a taskAssignedToUserId=1, after that I update taskAssignedToUserId in HttpClient Async Method but when I get out of method I do not get updated value of taskAssignedToUserId.
Code
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