First introduction to asynchronous programming

Table of contents

1. Write your own asynchronous method

2. Summary


1. Write your own asynchronous method

1. The HttpClient class is used to make http requests.

Because HttpClient implements the IDisposable interface, it must be recycled using using. (? Why? Doubtful!)

2. Obtain web page content: in the form of html

Assuming that the receiving type must be in html format, it will be received in string format. GetString has only asynchronous methods and no synchronous methods

3. Write the obtained html into filename from the folder

4. Return the length of the html file

5. Call this method in the Main method

The running result is:

 2. Summary

If there are both asynchronous and synchronous methods for the same function, then the asynchronous method is used first.

What to do about unsupported methods? Use a parameter of type Task<T> to receive its return value. Then add .Result in front of the return value.

In this case, Microsoft automatically helps us get the Result of the return value str.

 You can also use the Wait() method:

However, this situation has the risk of deadlock, so this is not recommended. 

Guess you like

Origin blog.csdn.net/2201_75837601/article/details/128475683