use*_*993 4 c# task-parallel-library async-await
我在以下代码中遇到两个错误:
public async Task<string> TestDownloadTask()
{
HttpResponseMessage response = null;
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(@"https://api.nasa.gov/planetary/apod");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response.EnsureSuccessStatusCode();
response = await client.GetStringAsync("?concept_tags=True&api_key=DEMO_KEY");
}
return response.Content;
}
Run Code Online (Sandbox Code Playgroud)
我越来越:
我一直在尝试编写上面的代码,它将从Web服务下载一个字符串,但似乎有很多关于如何使用async和await以及如何使用HttpClient的冲突信息,我不知道是什么问题用我编写的代码.
我哪里出错了,我应该怎么做呢?
此方法client.GetStringAsync返回Task<string>
public Task<string> TestDownloadTask()
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(@"https://api.nasa.gov/planetary/apod");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// You don't need await here
return client.GetStringAsync("?concept_tags=True&api_key=DEMO_KEY");
}
}
Run Code Online (Sandbox Code Playgroud)
要使用上述功能:
public async void SomeMethod()
{
// await to get string content
string mystring = await TestDownloadTask();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18019 次 |
| 最近记录: |