Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The return type of an async method must be void, Task or Task<T> [closed]

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.

like image 850
Tamas Ionut Avatar asked Mar 08 '16 21:03

Tamas Ionut


People also ask

What is the return type of async await?

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.

Is an async method that returns task?

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.

Can async return void?

Event handlers naturally return void, so async methods return void so that you can have an asynchronous event handler.

Is an async method that returns task a return keyword must not be followed by an object?

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>'?


1 Answers

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;
like image 81
Lee Avatar answered Sep 20 '22 14:09

Lee