【发布时间】:2013-09-05 15:01:43
【问题描述】:
我希望我的程序遵循这个调用堆栈/工作流程:
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 种方法都设为非异步,将 httpPost 中的 awaits 替换为 .Results,但随后它会永远挂在行上 HttpResponseMessage response = httpClient.PostAsync(url, new FormUrlEncodedContent(parameters)).Result;
谁能启发我并解释我的错误是什么?
【问题讨论】:
标签: c# .net http async-await