1

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  
J Smith
  • 27
  • 6
  • 1
    Can you show how you're calling the method. – stuartd Sep 13 '18 at 09:34
  • Why would you set a variable instead of having `PostRequestUserId` return the value? – NineBerry Sep 13 '18 at 09:34
  • @stuartd `PostRequestUserId(Constants.basePath, Constants.apiKey, Constants.deviceToken, Constants.deviceType, "Steve");` – J Smith Sep 13 '18 at 09:39
  • Possible duplicate of [Calling async method does not set member variable](https://stackoverflow.com/questions/16785336/calling-async-method-does-not-set-member-variable) – NineBerry Sep 13 '18 at 09:41
  • you perhaps need to await a call – dipak Sep 13 '18 at 09:42
  • @NineBerry I send username and get his his **ID(taskAssignedToUserId)**, to update this old ID with this ID I need to use variable – J Smith Sep 13 '18 at 09:45
  • @stuartd i am calling the method in same class and when i use await it says await can only be used in async method, here is statement `var newId = await PostRequestUserId(Constants.basePath, Constants.apiKey, Constants.deviceToken, Constants.deviceType, "Steve");` – J Smith Sep 13 '18 at 11:11
  • You're getting that error because your method signature is `async void` - it has to return a `Task` to be awaitable. See the answer below. [This question](https://stackoverflow.com/questions/12144077/async-await-when-to-return-a-task-vs-void) has a lot more info on that. – stuartd Sep 13 '18 at 11:21
  • @stuartd I have already changed the signatures to `public async static Task PostRequestUserId(string url, string api_key, string device_token, string device_type, string username) {code....}` – J Smith Sep 13 '18 at 11:24
  • That suggests that the method you're calling `PostRequestUserId` is not **itself** async. Is it an event handler? They are the one case where `async void` is appropriate. If not then, well, it gets a bit complicated as you can either a) make your codebase async or b) start using `Wait` or `Result` on the returned task, both of which have some subtle implications. – stuartd Sep 13 '18 at 11:57
  • @stuartd **Problem Solved** I was calling `PostRequestUserId` in a `void` function. I just put `async` before `void` and problem solved. **I really appreciate all of you** – J Smith Sep 13 '18 at 12:23

1 Answers1

1

You should modify your code like this:

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
}

and in some other class in some other method:

var newId = await MyStaticClass.PostRequestUserId(input_values...);
MessageBox.Show(newId);
maximelian1986
  • 2,308
  • 1
  • 18
  • 32
  • Thanks, missed it. – maximelian1986 Sep 13 '18 at 09:48
  • I am sorry for delaying in reply because I am new here on stackOverflow and don't know to use it efficiently. **I am giving importance to all of your answers/comments** – J Smith Sep 13 '18 at 09:51
  • i am calling the method in same class and when i use **await** it says **await** can only be used in **async** method, here is statement `var newId = await PostRequestUserId(Constants.basePath, Constants.apiKey, Constants.deviceToken, Constants.deviceType, "Steve");` – J Smith Sep 13 '18 at 10:56
  • **Problem Solved** I was calling `PostRequestUserId` in a `void` function. I just put `async` before `void` and problem solved. **I really appreciate all of you** – J Smith Sep 13 '18 at 12:24