异步方法的返回类型必须是 void、Task 或 Task<T> [英] The return type of an async method must be void, Task or Task<T>

查看:39
本文介绍了异步方法的返回类型必须是 void、Task 或 Task<T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有以下代码:

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;
}

async Task<HttpResponseMessage> GetResponseAsync(byte[] requestData, HttpClient client, string uri) {...}

async Task<Dictionary<string, float>> ParseResponseAsync(HttpResponseMessage response) {...}

基本上在 GetResponseAsync 完成后,我想获取结果并将其提供给 ParseResponseAsync 并获取带有结果的任务.

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

async 方法的返回类型必须是 void、Task 或 Task

The return type of an async method must be void, Task or Task

实现此目标并消除此错误的最佳方法是什么?欢迎使用其他(更好的解决方案),也欢迎在最后一个 ContinueWith 中解释为什么要执行 task.Result.Result.

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.

推荐答案

将返回类型更改为Task>:

public async Task<Dictionary<string, float>> GetLikelihoodsAsync(List<string> inputs)

您也可以将 ContinueWith 的用法替换为 await:

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;

这篇关于异步方法的返回类型必须是 void、Task 或 Task&lt;T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆