Synchronous call of asynchronous methods in HttpClient and httpclient
In System. Net. Http, httpClient that uses Http to communicate with remote servers is provided, but it is asynchronous. Sometimes we do not need to use asynchronous operations. You can use the following method for Synchronous calling.
Class Program {static void Main (string [] args) {string _ address = "http://api.worldbank.org/countries? Format = json "; // Create an HttpClient instance HttpClient client = new HttpClient (); // obtain data remotely var task = client. getAsync (_ address); var rep = task. result; // here the task will be returned. // Read the response Content var task2 = rep. Content. ReadAsStringAsync (); var ret = task2.Result; // wait for the task to return here. Console. WriteLine (ret); Console. WriteLine ("Hit ENTER to exit..."); Console. ReadLine ();}}
The Asynchronous Operation of the main thread is not blocked. For more information, see HttpClient.