When we use network requesting, always use escaping closure to complete the data passed from net to our UI, though that generally works, but when getting into some intricate cases, we need to use nested clousure, which is not elegant, so study Threading Control Tech is useful for us to code better.
For example, we need to request a Image from internet, we can request data in the background, and allow UI moves quickly in the main thread, after fetched data, refresh the Image Control in main thread.
From Swift3 we really step into the world of Multi Threading Coding, where we have elegant grammer unlike the infrastructure developing with C in the past, Apple provided brand new grammer for us. However that is 3 or 4 years ago, now we just use several lines we can complete our tasks.
GCD is the logogram of Grand Central Dispatch, the main part of it is
Dispatch Queue. Queue can be regard as a assembly line in a factory. If we adding tasks to one queue (or main queue), that calls one thread, if we created 2 or more queue, and allocate tasks to them, that calls multi thread.
At First, I have to introduce a concept calls
Dispatch Queue, which is called as Queue before, first we should import
Foundation, and initialize a queue waiting for task.
let queue = DispatchQueue(label: "zrzz.site")
The basic method of initialize
DispatchQueue has one parameter, label is decided by you, as long as it is unique.
Async, the logogram of
Asynchronize, as its literal meaning, we can make our queue run two tasks synchronously or asynchronously. To realize it better, plz run codes below and observe results.
We create one thread, let it syncly run a for loop, and let main thread (in the out side) use sync method, and Cpu exec our tasks by order.
What if we use async method? Let’s check.
As expected, two tasks run asyncly, that is multi thread.