سؤال

I have a PCl in which I want to make a async call usingg HttpClient. I coded like this

 public static async Task<string> GetRequest(string url)
    {            
        var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue };
        HttpResponseMessage response = await httpClient.GetAsync(url);
        return response.Content.ReadAsStringAsync().Result;
    }

But await is showing error "cannot await System.net.http.httpresponsemessage" like message.

If I use code like this than everything goes well but not in async way

public static string GetRequest(string url)
    {
        var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue };
        HttpResponseMessage response = httpClient.GetAsync(url).Result;
        return response.Content.ReadAsStringAsync().Result;
    }

I just want that this method executes in async way.

This is the screen shot:

enter image description here

هل كانت مفيدة؟

المحلول

Follow the TAP guidelines, don't forget to call EnsureSuccessStatusCode, dispose your resources, and replace all Results with awaits:

public static async Task<string> GetRequestAsync(string url)
{            
  using (var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue })
  {
    HttpResponseMessage response = await httpClient.GetAsync(url);
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadAsStringAsync();
  }
}

If your code doesn't need to do anything else, HttpClient has a GetStringAsync method that does this for you:

public static async Task<string> GetRequestAsync(string url)
{            
  using (var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue })
    return await httpClient.GetStringAsync(url);
}

If you share your HttpClient instances, this can simplify to:

private static readonly HttpClient httpClient =
    new HttpClient() { MaxResponseContentBufferSize = int.MaxValue };
public static Task<string> GetRequestAsync(string url)
{            
  return httpClient.GetStringAsync(url);
}

نصائح أخرى

If you are using a PCL platform that supports .net4 then I suspect you need to install the Microsoft.bcl.Async nuget.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top