I have a method to POST some data to server. Server may return aswer means I need change URL and send data to other server. I use for it HttpClient class from 4.5 framework. I use either do-while loop to repeat requests until I do not need redirecton. But there is a problem.
The question is why if I create HttpClient instance outside loop, second await didn’t happen and my programm get out of loop, but if I create HttpClient instance inside the loop again and again – all is fine? Can I reuse one HttpClient for several POST requsts inside do-while loop inside async method?
My working code sample:
public async Task<bool> GameLogin()
{
JToken r;
do
{
var clientHandler = new HttpClientHandler
{
CookieContainer = this.myCContainer,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
};
var client = new HttpClient(clientHandler);
client.DefaultRequestHeaders.Add("client-ver", Versoin);
client.DefaultRequestHeaders.Add("method", "SignIn");
client.DefaultRequestHeaders.Add("authKey", AppParams["auth_key"].ToString());
var content = new StringContent(this.SendStr);
var answer = await client.PostAsync(this.CurrentUrl, content);
var rawString = await answer.Content.ReadAsStringAsync();
DinamicData = JObject.Parse(rawString);
r = DinamicData["r"];
if (r == null) continue;
this.CurrentUrl = string.Format("http://{0}/main.ashx", r);
} while (r != null);
return DinamicData.Type != JTokenType.Null;
}
My did not working code sample:
public async Task<bool> GameLogin()
{
var clientHandler = new HttpClientHandler
{
CookieContainer = this.myCContainer,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
};
var client = new HttpClient(clientHandler);
client.DefaultRequestHeaders.Add("client-ver", Versoin);
client.DefaultRequestHeaders.Add("method", "SignIn");
client.DefaultRequestHeaders.Add("authKey", AppParams["auth_key"].ToString());
var content = new StringContent(this.SendStr);
JToken r;
do
{
var answer = await client.PostAsync(this.CurrentUrl, content);
var rawString = await answer.Content.ReadAsStringAsync();
DinamicData = JObject.Parse(rawString);
r = DinamicData["r"];
if (r == null) continue;
this.CurrentUrl = string.Format("http://{0}/main.ashx", r);
} while (r != null);
return DinamicData.Type != JTokenType.Null;
}
And my second code did not wait await in secont loop turn.
Okay, now we’ve got the exception…
I suspect the problem isn’t reusing the
HttpClient– it’s reusing this:I suspect that
contentis probably being disposed by theHttpClient‘s first call, which makes the second call fail.Just move that line inside the loop (it’s inside the loop in your working code), and I expect all will be well.