I have the following code here:
public async Dictionary<string, float> GetLikelihoodsAsync(List<string> inputs)
{
HttpClient client = new HttpClient();
string uri = GetUri();
string body = GetRequestBody(inputs);
byte[] requestData = Encoding.UTF8.GetBytes(body);
Dictionary<string, float> result = await GetResponseAsync(requestData, client, uri)
.ContinueWith(responseTask => ParseResponseAsync(responseTask.Result))
.ContinueWith(task => task.Result.Result);
return result;
}
with
async Task<HttpResponseMessage> GetResponseAsync(byte[] requestData, HttpClient client, string uri) {...}
async Task<Dictionary<string, float>> ParseResponseAsync(HttpResponseMessage response) {...}
Basically after GetResponseAsync completes I want to take the results and feed it to ParseResponseAsync and get a task with the results of it.
Currently, it gives an compiler error saying
The return type of an async method must be void, Task or Task
What is the best way to achieve this goal and get rid of this error? Other (better solutions) are welcomed and some explanations of why do task.Result.Result in the last ContinueWith are also welcomed.
The behavior of async / await is similar to combining generators and promises. Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.
Async methods can have the following return types: Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value. void , for an event handler.
Event handlers naturally return void, so async methods return void so that you can have an asynchronous event handler.
DoSomething()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'?
Change the return type to Task<Dictionary<string, float>>
:
public async Task<Dictionary<string, float>> GetLikelihoodsAsync(List<string> inputs)
you can also replace your usage of ContinueWith
to use await
:
var response = await GetResponseAsync(requestData, client, uri);
var result = await ParseResponseAsync(response);
return result;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With