What are synchronous and asynchronous methods and how do you use them?

Sometimes we expect an answer or a result right away. And sometimes, it might take a while. And sometimes, what we thought would be quick turns out to take longer.

If I ask you what’s the current time, then I expect some kind of answer even if that answer is “I don’t know.” And if I ask you for a favor, then I usually expect that you’ll start soon but probably not right away. What if you’re in the middle of an important phone call and I ask you for the time? It might take a little longer, right? Or if the favor is small and you’re not doing anything at the moment, then you might be glad to help immediately.

The point is, we can’t be sure how long something will take in the real world and the same thing is true in programming. A method that runs right away is called synchronous. And a method that runs later is called asynchronous.

The asynchronous method doesn’t exactly run later. It’s actually composed of two parts. The first part is a normal synchronous method that you can call and expect an immediate answer. The difference is that the method will start a new thread to perform the requested action. What you get back right away isn’t the result you want but instead information that will let you get your desired outcome later.

This frees the calling code to be able to do other tasks and periodically wait for the asynchronous task to complete.