…
測試程式
private async Task<string> GetE0501JsonStringAsync()
{
HttpClient _httpClient = new HttpClient();
Logger.Info($"1={Thread.CurrentThread.ManagedThreadId}");
var jsonString =
await _httpClient.GetStringAsync(@"https://localhost:44300/api/v1/e0501/");
Logger.Info($"2={Thread.CurrentThread.ManagedThreadId}");
return jsonString;
}
public async Task<ActionResult> ImportByUrl(int id)
{
Logger.Info($"0={Thread.CurrentThread.ManagedThreadId}");
var e0501 = GetE0501JsonString().Result;
Logger.Info($"3={Thread.CurrentThread.ManagedThreadId}");
}
執行結果
2023/10/19 13:36:11
0=5
2023/10/19 13:36:13
1=5
修改程式, 在呼叫處也加上await
public async Task<ActionResult> ImportByUrl(int id)
{
Logger.Info($"0={Thread.CurrentThread.ManagedThreadId}");
var e0501 = await GetE0501JsonString();
Logger.Info($"3={Thread.CurrentThread.ManagedThreadId}");
}
執行結果
2023/10/19 11:29:11
0=8
2023/10/19 11:30:21
1=8
2023/10/19 11:30:27
2=24
--> HttpClient create new thread.
所以呼叫處也要await, 因為old thread已經往下go.
2023/10/19 11:30:33
3=24