Using the addOperation() method of the operation queue

The OperationQueue class has a method named addOperation(), which makes it easy to add a block of code to the queue. This method automatically wraps the block of code in an operation object and then passes that operation to the queue. Let's see how to use this method to add tasks to a queue:

let operationQueue = OperationQueue() 
let calculation = DoCalculations()
operationQueue.addOperation() { calculation.performCalculation(10000000, tag: "Operation1") } operationQueue.addOperation() { calculation.performCalculation(10000, tag: "Operation2") } operationQueue.addOperation() { calculation.performCalculation(1000000, tag: "Operation3") }

In the BlockOperation example, earlier in this chapter, we added the tasks that we wished to execute into a BlockOperation instance. In this example, we are adding the tasks directly to the operation queue, and each task represents one complete operation. Once we create the instance of the operation queue, we then use the addOperation() method to add the tasks to the queue.

Also, in the BlockOperation example, the individual tasks did not execute until all of the tasks were added, and then that operation was added to the queue. This example is similar to the GCD example where the tasks began executing as soon as they were added to the operation queue.

If we run the preceding code, the output should be similar to this:

time for Operation2: 0.0115870237350464
time for Operation3: 0.0790849924087524
time for Operation1:  0.520610988140106

You will notice that the operations are executed concurrently. With this example, we can execute the tasks serially by using the maxConcurrentOperationCount property that we mentioned earlier. Let's try this by initializing the OperationQueue instance as follows:

var operationQueue = OperationQueue() 
operationQueue.maxConcurrentOperationCount = 1 

Now, if we run the example, the output should be similar to this:

time for Operation1:  0.418763995170593 
time for Operation2:  0.000427007675170898
time for Operation3:  0.0441589951515198  

In this example, we can see that each task waited for the previous task to complete prior to starting.

Using the addOperation() method to add tasks to the operation queue is generally easier than using the BlockOperation method; however, the tasks will begin as soon as they are added to the queue. This is usually the desired behavior, although there are use cases where we do not want the tasks executing until all operations are added to the queue, as we saw in the BlockOperation example.

Now, let's look at how we can subclass the Operation class to create an operation that we can add directly to an operation queue.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset