0

I am working on a Winforms app that makes some HTTP based API calls to various web services within a Timer control loop. The web services are called using the async keyword. The problem is that I get a Threading exception when attempting to return the result as a string.

private async Task<String> UpdateViaApi(ClientInfoObject clientInfoObject)
{
    HttpResponseMessage response = await myHttpClient.SendAsync(request);
    string result = await response.Content.ReadAsStringAsync();
    return result;
}

Here is how I call the method ...

string result = UpdateViaApi(clientInfoObject);

The ClientInfoObject is a simple class that contains data as a series of properties. Am I using Task properly?

2
  • 1
    That won't even compile. UpdateViaApi returns a Task<string> not a string. Commented Jul 28, 2014 at 17:08
  • I see your point. However, it does compile. Commented Jul 28, 2014 at 17:12

1 Answer 1

4

You need to await the returned task:

string result = await UpdateViaApi(clientInfoObject);

Also, note that the method name should end in Async, to conform to the convention:

string result = await UpdateViaApiAsync(clientInfoObject);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the response. When I add the keyword await I get the error The await operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. Also, reading your book at the moment. Good information.
@webworm Now did you read the error message and follow the instructions that it gave you?
Indeed I did. Looks like the method that contained UpdateViaApiAsync(clientInfoObject) also need to be prefixed with the await operator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.