Tam*_*nut 9 c# asynchronous task task-parallel-library async-await
我在这里有以下代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
同
async Task<HttpResponseMessage> GetResponseAsync(byte[] requestData, HttpClient client, string uri) {...}
async Task<Dictionary<string, float>> ParseResponseAsync(HttpResponseMessage response) {...}
Run Code Online (Sandbox Code Playgroud)
基本上在GetResponseAsync完成之后,我想获取结果并将其提供给ParseResponseAsync并获得包含结果的任务.
目前,它给编译器错误说
异步方法的返回类型必须为void,Task或Task
实现这一目标并消除此错误的最佳方法是什么?其他(更好的解决方案)受到欢迎,并且为什么task.Result.Result在最后的ContinueWith中的一些解释也受到欢迎.
Lee*_*Lee 16
将返回类型更改为Task<Dictionary<string, float>>:
public async Task<Dictionary<string, float>> GetLikelihoodsAsync(List<string> inputs)
Run Code Online (Sandbox Code Playgroud)
你也可以更换您的使用情况ContinueWith来使用await:
var response = await GetResponseAsync(requestData, client, uri);
var result = await ParseResponseAsync(response);
return result;
Run Code Online (Sandbox Code Playgroud)
Ged*_*tis 11
如错误中所述:
异步方法的返回类型必须是
void,Task或Task<T>
在您的情况下Task<T>,或将具体Task<Dictionary<string, float>>.所以,你的方法需要声明为:
public async Task<Dictionary<string, float>> GetLikelihoodsAsync(List<string> inputs)
Run Code Online (Sandbox Code Playgroud)
请注意,您实际上不需要返回a Task<T>,您只需要返回T.你可以在这里阅读更多相关信息.
| 归档时间: |
|
| 查看次数: |
17407 次 |
| 最近记录: |