Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this HttpClient usage giving me an "Cannot access a disposed object." error?

Tags:

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.

like image 995
Mr J Avatar asked Apr 18 '16 15:04

Mr J


1 Answers

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)) {  } 
like image 65
CathalMF Avatar answered Sep 25 '22 07:09

CathalMF