Monday, July 8, 2013

Asynchronous Synchronization

Asynchronous is the way to go!
Blocking synchronization functions are evil!

Usually these statements are true. Especially when handling I/O, blocking function calls can bog down your code.

But there are exception.
Sometimes your application can only continue AFTER a file is opened / saved / closed / etc.
This is usually where completion handlers come in handy. With these you can perform actions after the opening / saving / etc has been completed.

But once in a while, you need everything to wait until some I/O is finished. How do you go about this.

Here's some magic:

 - (void)actionOnDocument:(void (^)(PDFDocument *pdfDoc))actionHandler  
 {  
   __block bool isFileOpened = NO;  
   [doc openWithCompletionHandler:^(BOOL success) {  
     if (success) {  
       actionHandler(doc.data);  
       // save and close  
       [doc saveWithCompletion:^(BOOL success) {  
         isFileOpened = YES;  
       }];  
     }  
     else {  
       actionHandler(nil);  
       isFileOpened = YES;  
     }  
   }];  
   // loop-lock  
   while(!isFileOpened){  
     [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];  
   }  
 }  

As you see, we want to perform some kind of action on a PDFDocument. However, we also want to make sure that the application does not continue before this function is completed (and the document is closed again).

The secret here is to run a check in a loop. Of course this loop should not check continually as that would suck up all resources. Instead we check every little while if something has changed in the status of the isFileOpened value.

Now we build synchronization into an asynchronous function.

Have Fun & Keep Koding!  
Freek Sanders.
MakeMeBlue

No comments:

Post a Comment