私は自分のプログラムがこのコールスタック/ワークフローに従うことを望んでいます:
dispatch()
authorize()
httpPost()
私の考えではhttpPost()
、他の 2 つのメソッドは非同期のままですが、それは非同期になります。しかし、なぜか2と3をasyncにしないと動かない。もしかしたら、まだ誤解があるかもしれません。
私の理解では、次のいずれかを実行できます。
- async メソッドを呼び出すときにキーワードを使用する
await
(これにより、メソッドが一時停止され、async メソッドの完了後に続行されます)、または 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);
}
await
また、3 つのメソッドすべてを非非同期にして、 shttpPost
をsに置き換えようとし.Result
ましたが、回線上で永久にハングします。HttpResponseMessage response = httpClient.PostAsync(url, new FormUrlEncodedContent(parameters)).Result;
誰かが私を啓発し、私の間違いが何であるかを説明できますか?