Multithreaded Programming 2-nsoperation

Source: Internet
Author: User

First, Nsoperation

1. Introduction

The Nsoperation instance encapsulates the required actions and the data required to perform the operation, and can perform this operation in a concurrent or non-concurrent manner.

The nsoperation itself is an abstract base class, so it must use its subclasses, and there are 2 ways to use the Nsoperation subclass:

The 1> Foundation framework provides two specific subclasses directly for our use: Nsinvocationoperation and Nsblockoperation

2> Custom subclass Inherits Nsoperation, implements the internal corresponding method

2. Perform the action

Nsoperation calls the Start method to begin the operation, and the Nsoperation object is executed synchronously by default, which is executed directly in the thread that called the Start method. The Isconcurrent method of the Nsoperation object tells us whether the operation is synchronous or asynchronous, relative to the thread that called the Start method. The Isconcurrent method returns no by default, indicating that the operation is performed synchronously with the calling thread

3. Cancel the operation

After the operation has started executing, the operation continues until it is completed, and we can call the Cancel method halfway through the operation

[Java]View Plaincopy
    1. [Operation Cancel];

4. Execution of the listening operation

If we want to do something after a nsoperation executes, call Nsoperation's Setcompletionblock method to set what we want to do.

[Java]View Plaincopy
    1. Operation.completionblock = ^ () {
    2. NSLog (@"execution complete");
    3. };


Or

[Java]View Plaincopy
    1. [Operation Setcompletionblock:^ () {
    2. NSLog (@"execution complete");
    3. }];

Second, nsinvocationoperation

1. Introduction

Creates an action based on an object and selector. If you already have an existing method to perform the required tasks, you can use this class

2. Create and perform actions

[Java]View Plaincopy
    1. This is done by calling the Run method of self
    2. Nsinvocationoperation *operation = [[Nsinvocationoperation alloc] initwithtarget:self selector:@selector (Run)  Object:nil];
    3. Start task Execution (synchronous execution)
    4. [Operation start];


Third, nsblockoperation

1. Introduction

Ability to execute one or more block objects concurrently, after all the relevant blocks have been executed, the operation is completed

2. Create and perform actions

[Java]View Plaincopy
    1. Nsblockoperation *operation = [Nsblockoperation blockoperationwithblock:^ () {
    2. NSLog (@"performed a new operation, thread:%@", [Nsthread CurrentThread]);
    3. }];
    4. //Start a task (this is still done synchronously)
    5. [Operation start];

3. Adding a block operation via the Addexecutionblock method

[Java]View Plaincopy
  1. Nsblockoperation *operation = [Nsblockoperation blockoperationwithblock:^ () {
  2. NSLog (@"performing the 1th operation, Thread:%@", [Nsthread CurrentThread]);
  3. }];
  4. [Operation Addexecutionblock:^ () {
  5. NSLog (@"performed 1 new operations, Thread:%@", [Nsthread CurrentThread]);
  6. }];
  7. [Operation Addexecutionblock:^ () {
  8. NSLog (@"performed 1 new operations, Thread:%@", [Nsthread CurrentThread]);
  9. }];
  10. [Operation Addexecutionblock:^ () {
  11. NSLog (@"performed 1 new operations, Thread:%@", [Nsthread CurrentThread]);
  12. }];
  13. Start to perform a task
  14. [Operation start];

Print the following information:

[Java]View Plaincopy
  1. 2013-02-: 46.102 thread[4602:c07] 1 new operations were performed, Threads: <nsthread: 0x7121d50> {name = (null), num = 1}
  2. 2013-02-: 46.102 thread[4602:3f03] 1 new operations were performed, Threads: <nsthread: 0x742e1d0>{name = (null), num = 5}
  3. 2013-02-02  21:38:46.102 thread[ 4602:1b03]  performing 1 operations, Threads: <nsthread: 0x742de50>{name  =  (null),  num = 3}&NBSP;&NBSP;
  4. 2013-02-: 46.102 thread[4602:1303] 1 new operations were performed, thread: <nsthread: 0x7157bf0>{name = (null), num = 4}

As you can see, these 4 blocks are executed concurrently, that is, executed in different threads, and the NUM attribute can be seen as the ID of the thread.

Iv. Custom Nsoperation

1. Introduction

If the nsinvocationoperation and Nsblockoperation objects do not meet the requirements, you can directly inherit the nsoperation and add any behavior you want. The amount of work required for inheritance depends primarily on whether you want to implement non-concurrency or concurrency nsoperation. It is much simpler to define non-concurrent nsoperation, only the overloaded-(void) Main method, which executes the main task in this method and responds correctly to the cancellation event; For concurrent nsoperation, you have to rewrite the nsoperation of the basic methods to implement (here, for the time being the non-concurrent nsoperation)

2. Non-concurrent Nsoperation

For example, called downloadoperation, used to download images

1> inherits Nsoperation, overrides Main method, executive Director

DownloadOperation.h

[Java]View Plaincopy
  1. #Import <Foundation/Foundation.h>
  2. @protocol downloadoperationdelegate;
  3. @interface downloadoperation:nsoperation
  4. URL path of the picture
  5. @property (nonatomic, copy) NSString *imageurl;
  6. Agent
  7. @property (nonatomic, retain) id<downloadoperationdelegate> delegate;
  8. -(ID) Initwithurl: (nsstring *) URL delegate: (id<downloadoperationdelegate>) delegate;
  9. @end
  10. Agreement for picture Download
  11. @protocol downloadoperationdelegate <NSObject>
  12. -(void) Downloadfinishwithimage: (UIImage *) image;
  13. @end


Downloadoperation.m

[Java]View Plaincopy
  1. #Import "DownloadOperation.h"
  2. @implementation Downloadoperation
  3. @synthesize delegate = _delegate;
  4. @synthesize imageUrl = _imageurl;
  5. Initialization
  6. -(ID) Initwithurl: (nsstring *) URL delegate: (id<downloadoperationdelegate>) Delegate {
  7. if (self = [Super init]) {
  8. Self.imageurl = URL;
  9. Self.delegate = delegate;
  10. }
  11. return self;
  12. }
  13. Freeing memory
  14. -(void) Dealloc {
  15. [Super Dealloc];
  16. [_delegate release];
  17. [_imageurl release];
  18. }
  19. Executive Director Services
  20. -(void) Main {
  21. //Create a new auto-release pool, which will not be accessible to the main thread's auto-release pool If the operation is performed asynchronously
  22. @autoreleasepool {
  23. // ....  
  24. }
  25. }
  26. @end

2> correct response to cancellation events

After operation begins execution, the task continues until it is completed, or the operation is explicitly canceled. Cancellation can occur at any time, even before operation is executed. Although Nsoperation provides a way for the application to cancel an operation, it is our own business to identify the cancellation event. If operation is terminated directly, all allocated memory or resources may not be reclaimed. So the operation object needs to detect the cancellation event and gracefully exit the execution

The Nsoperation object needs to periodically call the IsCancelled method to detect if the operation has been canceled, and if Yes is returned (indicating cancellation), exit execution immediately. Whether you are customizing the Nsoperation subclass or using the two specific subclasses provided by the system, you need to support cancellation. The IsCancelled method itself is very lightweight and can be called frequently without large performance loss

You may need to call iscancelled in the following places:
* Before any actual work is performed
* During each iteration of the loop, if each iteration is relatively long, it may need to be called multiple times
* The code is relatively easy to abort the operation anywhere

The main method of Downloadoperation is implemented as follows

[Java]View Plaincopy
    1. -(void) Main {
    2. //Create a new auto-release pool, which will not be accessible to the main thread's auto-release pool If the operation is performed asynchronously
    3. @autoreleasepool {
    4. if (self.iscancelled) return;
    5. //Get Picture data
    6. Nsurl *url = [Nsurl URLWITHSTRING:SELF.IMAGEURL];
    7. NSData *imagedata = [NSData Datawithcontentsofurl:url];
    8. if (self.iscancelled) {
    9. url = nil;
    10. ImageData = nil;
    11. return;
    12. }
    13. //Initialize picture
    14. UIImage *image = [UIImage imagewithdata:imagedata];
    15. if (self.iscancelled) {
    16. image = Nil;
    17. return;
    18. }
    19. if ([self.delegate respondstoselector:@selector (downloadfinishwithimage:)]) {
    20. //Transfer the image data back to the main thread
    21. [(NSObject *) self.delegate performselectoronmainthread:@selector (downloadfinishwithimage:) withobject:image  Waituntildone:no];
    22. }
    23. }
    24. }

Multithreaded Programming 2-nsoperation

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.