【发布时间】:2016-09-07 18:19:14
【问题描述】:
我有一个与内部 Web API 交互的控制台应用程序。它有时运行正确,但有时它会无缘无故地抛出异常,我找不到。我唯一的怀疑是,可能是因为我使用的每个方法都不是异步的。
从这里开始:
我的控制台应用程序运行异步方法 Process():
static void Main(string[] args)
{
Process().Wait();
}
Process() 连接到内部网络应用程序:
private static async Task Process()
{
using (var http = new HttpClient())
{
http.BaseAddress = new Uri("http://localhost:112345/");
var response = await http.PostAsJsonAsync("/api/PostStuff", data);
var result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
}
这是内部网络 API:
[HttpPost("api/PostStuff")]
public async Task<string> PostStuff([FromBody] Data data)
{
foreach (var s in MyStuff.GetStuff()
{
// for loop that gets data from another class that is not asynchronous
}
return stuff;
}
我担心的是,从使用 MyStuff.GetStuff() 的循环中收集的数据使用的方法不是任务或异步的。
我是否需要确保异步方法中使用的每个方法也是异步的?
谢谢!
【问题讨论】:
标签: .net c#-4.0 async-await