In C #, what is a synchronous alternative for the HttpClient.getStringAsync () method?

In winform, clicking a button calls this method to load the contents of the link as a string, and then displays the length of the string in the text box. All this happens asynchronously. Is there any way to do this synchronously?

+5
source share
3 answers

You can do any task block by simply clicking .Result :

 string response = client.GetStringAsync(...).Result; 

However, if this works in the user interface thread, you should not do this. Locking on the user interface thread is not very pleasant. Declare asynchrony.

+10
source

You can use the WebClient.DownloadString method. This method is blocked when loading a resource.

 string response = new WebClient().DownloadString(uri); 

https://msdn.microsoft.com/en-us/library/fhd1f0sw(v=vs.110).aspx

+3
source

RestSharp is a good open source alternative to HttpClient. It supports both synchronization requests and asynchronous requests.

http://restsharp.org/

+1
source

Source: https://habr.com/ru/post/1244537/


All Articles