我希望我的程序遵循这个调用堆栈/工作流程:
dispatch()
authorize()
httpPost()
我的想法是这httpPost()
将是异步的,而其他 2 种方法仍然是非异步的。但是,由于某种原因,除非我使 2 和 3 异步,否则它将无法工作。也许我还有一些误解。
据我了解,我可以:
- 在调用异步方法时使用
await
关键字(这将暂停该方法并在异步方法完成后继续),或者 - 省略
await
关键字,而是调用Task.Result
异步方法返回值,这将阻塞直到结果可用。
这是工作示例:
private int dispatch(string options)
{
int res = authorize(options).Result;
return res;
}
static async private Task<int> authorize(string options)
{
string values = getValuesFromOptions(options);
KeyValuePair<int, string> response = await httpPost(url, values);
return 0;
}
public static async Task<KeyValuePair<int, string>> httpPost(string url, List<KeyValuePair<string, string>> parameters)
{
var httpClient = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await httpClient.PostAsync(url, new FormUrlEncodedContent(parameters));
int code = (int)response.StatusCode;
response.EnsureSuccessStatusCode();
string responseString = await response.Content.ReadAsStringAsync();
return new KeyValuePair<int, string>(code, responseString);
}
这是非工作示例:
private int dispatch(string options)
{
int res = authorize(options).Result;
return res;
}
static private int authorize(string options)
{
string values = getValuesFromOptions(options);
Task<KeyValuePair<int, string>> response = httpPost(url, values);
doSomethingWith(response.Result); // execution will hang here forever
return 0;
}
public static async Task<KeyValuePair<int, string>> httpPost(string url, List<KeyValuePair<string, string>> parameters)
{
var httpClient = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await httpClient.PostAsync(url, new FormUrlEncodedContent(parameters));
int code = (int)response.StatusCode;
response.EnsureSuccessStatusCode();
string responseString = await response.Content.ReadAsStringAsync();
return new KeyValuePair<int, string>(code, responseString);
}
我还尝试让所有 3 种方法都非异步,将await
shttpPost
替换为.Result
s,但随后它永远挂在了线上HttpResponseMessage response = httpClient.PostAsync(url, new FormUrlEncodedContent(parameters)).Result;
有人可以启发我并解释我的错误是什么吗?