IOS NSOperation non-concurrent execution, iosnsoperation

Source: Internet
Author: User

IOS NSOperation non-concurrent execution, iosnsoperation
NSOperation provides an object-oriented method to encapsulate tasks. NSOperation can be executed independently or in NSOperationQueue. NSOperation is a virtual base class that cannot be used directly, but Cocoa provides two simple subclass NSBlockOperation and NSInvocationOperation. NSBlockOperation encapsulates a task into a block object, and NSInvocationOperation encapsulates the task to selector. NSBlockOperation-(void) startOperation
{
NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "NSBlockOperation Test") ;}]; [operation start];} call the start method to start the task, NSOperation's instance method cancel can cancel ongoing tasks, which is advantageous over GCD (GCD does not provide the function to cancel tasks ). However, it is not as simple as we think to call a cancel Method. Let's look at the following code:-(void) startOperation.
{
NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock: ^ {
While (1 ){
NSLog (@ "Test operation cancel funcation ");
}]; [Operation start]; [operation cancel];} after the start method is called, The while loop will always be executed, and then the cancel method will be called. Will the while LOOP stop? The answer is no, because the cancel method will not be executed, and the current thread is stuck in the block task. You may want to call the cancel Method of the instance after setting the 0.01s delay before the start method? See the following code:-(void) startOperation
{
NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock: ^ {
While (1 ){
NSLog (@ "Test operation cancel funcation ");
}
}]; Self. operation = operation; [self defined mselector: @ selector (cancelOperation) withObject: nil afterDelay: 0.01f]; [operation start];}-(void) cancelOperation
{
[Self. operation cancel];} The cancelOperation method is not called during actual operation. Why? NSOperation does not provide multithreading. The task is executed asynchronously in the current thread, and the subsequent code is executed only after the task is executed. The cancel method is written in the current thread, and the current thread is stuck in the while loop, so the cancel method will not be called at all. Since the endless loop tasks cannot be canceled in the same thread, do you need to put the tasks in the background and cancel them in the main thread? NSOperationQueue provides the multi-thread capability to put the NSOperation task into the queue for execution. See the following code:-(void) startOperation
{
NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock: ^ {
While (1 ){
NSLog (@ "Test operation cancel funcation ");
}
}];

Self. operation = operation;

NSOperationQueue * queue = [[NSOperationQueue alloc] init];
[Queue addOperation: operation];
// [Operation cancel];

[Self defined mselector: @ selector (cancelOperation) withObject: nil afterDelay: 0.01f];} The cancelOperation method is omitted as above, the operation task is added to the NSOperationQueue and the next Runloop is executed. if the task is canceled immediately after the addition, the task is not executed. So we put it in the delay method to cancel operation. In this way, you can always exit the while loop! The test shows that the while loop is still being executed. Why? In the official documents of Apple, the NSOperation statement is as follows: If an operation were terminated outright, there might not be a way to reclaim resources that had been allocated. as a result, operation objects are expected to check for cancellation events and to exit gracefully when they occur in the middle of the operation. generally, the task is interrupted, but the allocated memory resources may not be recycled. Therefore, you must check whether the task is canceled before executing the task. In addition, ensure that the allocated memory is released after the task is canceled. Pay special attention to this in the NSOperation subclass. Which of the following is true?-(void) startOperation
{
_ Weak ViewController * wself = self;

NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock: ^ {
While (wself. operation. isCancelled = NO ){
NSLog (@ "Test operation cancel funcation ");
}
}];

Self. operation = operation;

NSOperationQueue * queue = [[NSOperationQueue alloc] init];
[Queue addOperation: operation]; [self defined mselector: @ selector (cancelOperation) withObject: nil afterDelay: 0.01f];} All of the above are subclasses of NSOperation provided by the system, we can also define a new subclass. NSOperation tasks are non-Concurrently executed by default. The read-only attribute BOOL concurrent (BOOL asynchronous after iOS7) returns NO by default. Before using NSOperationQueue, we should first understand several concepts: threads, synchronization, Asynchronization, and concurrent threads are the smallest units of program execution, an entity in the process, and the basic unit of independent scheduling and distribution by the system, multiple threads in the same process can be executed concurrently. Thread Synchronization is a process where multiple threads compete for resources and need to be accessed in sequence. Thread Asynchronization means that multiple threads can simultaneously access the same resource and execute the code after the task is completed, after an asynchronous call is made, the subsequent code is executed. The actual execution of the call is completed later, such as the callback mselector call. Concurrent execution refers to the code that can be executed without waiting for the task to finish. I used NSOperationQueue above to process multi-thread queues at the top layer of cocoa. NSOperationQueue opens a new thread for each added NSOperation task, and destroys the thread after the task is executed. Multiple tasks are executed asynchronously, which is an asynchronous queue. However, you can set the maximum number of tasks simultaneously executed by NSOperationQueue to 1 (maxConcurrentOperationCount = 1) for Synchronous queues. Non-concurrent tasks are added to the NSOperationQueue queue for asynchronous execution. Therefore, if you need to add the NSOperation task to the NSOperationQueue queue, you do not need to implement the NSOperation concurrent task. The custom NSOperation subclass and concurrent implementation tasks will be discussed in the next section.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.