I've simplified the code a bit but basically this keep giving me a "Cannot access a disposed object." error and I cant work out why?
I have multiple tasks running simultaneously that perform a GET then parse some HTML then perform a POST depending on the results of the GET.
The method this code resides in returns an event object with results so I don't think I can use await because the method would need to return void?
foreach (Account accountToCheck in eventToCheck.accountsToRunOn) { Task.Run(() => { HttpClientHandler handler = new HttpClientHandler(); CookieContainer cookies = new CookieContainer(); handler.CookieContainer = cookies; using (var client = new HttpClient(handler)) { ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; client.Timeout = new TimeSpan(0, 0, 3); client.DefaultRequestHeaders.Add("Keep-Alive", "false"); HttpResponseMessage response = client.GetAsync("https://test.com", HttpCompletionOption.ResponseContentRead).Result; string html = response.Content.ReadAsStringAsync().Result; var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("test[username_or_email]", accountToLogIn.accountHandle), new KeyValuePair<string, string>("test[password]", accountToLogIn.accountPassword) }); var loginPostResult = client.PostAsync("https://test.com/login", content).Result; loginHTMl = convertToUTF8(loginPostResult.Content.ReadAsStringAsync().Result); } }); }
Exception.
Unable to read data from the transport connection: Cannot access a disposed object.
Ok after a bit of research i found the issue. The HttpClientHandler will get disposed after the first request. You need to instruct your system not to dispose the handler.
Change your using to add false
to the constructor.
using (var client = new HttpClient(handler, false)) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With