0
我有一個與內部Web API交互的控制檯應用程序。它有時會正確運行,但有時它會拋出異常,我無法找到任何理由。我唯一的懷疑是,也許是因爲我使用的每種方法都不是異步的。異步方法和內部循環
這裏是它開始:
我的控制檯應用程序運行異步方法的工序():
static void Main(string[] args)
{
Process().Wait();
}
流程()連接到一個內腹板APPI:
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);
}
}
這裏是內部Web 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()的循環中收集的數據使用非任務或異步方法。
我是否需要確保異步方法中使用的每種方法都是異步的?
謝謝!
謝謝。我相信我需要做一切異步,因爲MyStuff.GetStuff()調用外部webAPI。因此,控制檯應用程序需要等待所有這些WebAPI內容完成才能向用戶提供數據。 – SkyeBoniwell