1

I am using the below code to read JSON from an endpoint in my Xamarin crossplatform project and I am getting error Cannot read disposed object exception or it fires ObjectDisposedException

IS it something wrong with code Can I write it in a better way ?

public async Task<APISchoolDetailModel> GetSchooDetailsAsync()
{
    APISchoolDetailModel api_data = new APISchoolDetailModel();
    try
    {
        var client = new System.Net.Http.HttpClient();
        client.DefaultRequestHeaders.Add("Accept", "application/json");
        var web_client = await client.GetAsync("http://appapitest.net/APIs/Student/Schooldetails");
        var response_string= web_client.Content.ReadAsStringAsync().Result;                                              
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(api_data.GetType());               
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(response_string));
        api_data = serializer.ReadObject(ms) as APISchoolDetailModel;
    }
    catch (Exception ex) { }            
    return api_data;
}

The controller comes till the line var web_client = await client.GetAsync(" and then its not going further and after few seconds I am getting exception

Is any better way to write this code for reading and parsing JSON

Sebastian
  • 4,625
  • 17
  • 76
  • 145
  • What is the exact line where you get that exception? Because I would expect that all your exceptions are swallowed based on the empty catch block. – rene Sep 18 '16 at 11:39
  • `var response_string = web_client.Content.ReadAsStringAsync().Result` - don't do that. Do `var response_string = await web_client.Content.ReadAsStringAsync()`. – GSerg Sep 18 '16 at 14:48
  • I am getting exception before that line. COntrol is not coming till this line – Sebastian Sep 18 '16 at 15:16
  • @rene pls see edit – Sebastian Sep 18 '16 at 15:19
  • 1
    @JibinMathew it might very well be that what GSerg said is the real root cause, given this: http://stackoverflow.com/a/24657079/578411 – rene Sep 18 '16 at 15:56

1 Answers1

0

@Gserg pointed out something important you should not do this:

var response_string= web_client.Content.ReadAsStringAsync().Result;

in stead of that use:

var response_string= await web_client.Content.ReadAsStringAsync();

within an async Task method:

is you use .Result this may be causing deadlocks within threads or the same stuff that you are experiencing because a thread may be trying to update or use a variable that is already collected from the GC.

Mario Galván
  • 3,964
  • 6
  • 29
  • 39
  • I changed the code , but still I am getting exception. And I am getting exception on line above ie var web_client = await client.GetAsync("http://appapitest.net/APIs/Student/Schooldetails"); – Sebastian Sep 19 '16 at 03:55