How to use HTTPClient Synchronusly?

winanjaya 146 Reputation points
2023-08-29T13:27:34.1+00:00

Hi All,

in some cases I need wait the HTTPClient's result, how to use it synchronusly?

mine was as follow:

bool _break = false;
int pageNo=1;
do 
{
   string url = baseAddress + $"/api/v7/labels?page={pageNo}&limit=1000";

   await _httpClient.GetAsync(url).ContinueWith(async (c) =>    
   {     var response = await c;   

        _break == response.IsSuccessStatusCode;

        if (response.IsSuccessStatusCode)
        {
            iStatusCode = (int)response.StatusCode;

            string _res = response.Content.ReadAsStringAsync().Result;

            if (!string.IsNullOrEmpty(_res))
            { 
               // do some processes             
            }          
         }
     } 

 pageNo++;
} while (!_break)
Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | Other
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2023-08-29T13:38:48.7733333+00:00

    Since you're already awaiting the response from the calling code I'm assuming that you mean that you want the lexical flow to appear synchronous, rather than synchronously blocking the calling thread. If that's correct then you can just move the response handling outside of the ContinueWith callback:

    bool _break = false;
    int pageNo = 1;
    do
    {
    	string url = baseAddress + $"/api/v7/labels?page={pageNo}&limit=1000";
    
    	HttpResponseMessage response = await _httpClient.GetAsync(url);
    
    	_break = response.IsSuccessStatusCode;
    
    	if (response.IsSuccessStatusCode)
    	{
    		iStatusCode = (int)response.StatusCode;
    
    		string _res = response.Content.ReadAsStringAsync().Result;
    
    		if (!string.IsNullOrEmpty(_res))
    		{
    			// do some processes             
    		}
    	}
    
    	pageNo++;
    } while (!_break);
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.