What is Asynchronicity?
It is the ability to do multiple things at the same time.
A thread is a thread of execution in a program. It is some programming that does something. When you have a user interface, it has a single thread that accepts user input from the user (in the form of events) and updates the user interface (rendering). This is known as the UI thread.
A synchronous operation blocks a process till the operation completes. If you add a synchronous operation to a UI thread then it stops the UI from repainting, responding etc. Bad idea. An example of this would be a button that the user hits and the program does some kind of heavy synchronous calculation. This will cause the UI to become frozen and unresponsive.
When writing code that does heavy lifting, developers need to use invoke asynchronous processes as worker threads. These will not block the UI thread and the UI will remain nice and responsive.
With asynchronous operations, another thread (a worker thread) is started to do some work and (once the work is finished), this thread returns the result to the UI thread, which can update the UI. Sometimes you can write worker threads that pass data little by little to the UI thread, incrementally updating the UI.
As a developer, you are not limited to two threads. You can have the UI thread plus as many worker threads as you need. Performing multiple operations in parallel can really make things faster. As you can see in the diagram below, the total time will be as long as required by the longest-running worker thread.
Once completed, asynchronous operations can result in Success (often with data) and Failure (often with error data). When the result is success, the UI thread can then update the UI with the results. When the result is failure, the UI thread can then update the UI to display an error to the user.
Sometimes you need to 'kick off' several asynchronous processes and wait until they are all completed to do something. Sometimes the calculation at the end requires all the data from all of the completed asynchronous processes. For example, you need to kick off 4 processes (like the diagram above) then wait for all 4 to finish before doing something at the end.
This is where a latch comes in. Latches are a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. In the diagram below we have 3 asynchronous processes and the latch is used to track when they are all completed.
Error HandlingRemember that error handling is more complicated. If you are invoking an asynchronous process you need to handle errors that occur when starting the asynchronous process and errors that occur inside the asynchronous process.
Enough overview for the moment. Next week we will go into more detail.