dispatch_async block not getting invoked - iphone

MySynchManager class is having a shared instance.
One of the function in MySynchManager class is
- (void)uploadSession:(NSString *)sessionId {
// run the upload process on a separate thread to not to block the main thread for user interaction
// process upload data in serial Queue
NSLog(#"Inside uploadSession");
if (!_serialQueue) {
NSLog(#"uploadSession, _serialQueue is NOT ACTIVE");
[self setRunLoopStarted:FALSE];
_serialQueue = dispatch_queue_create("sessionUploadQueue", NULL);
dispatch_async(_serialQueue, ^{
[[MySyncManager sharedInstance] dispatchSession:sessionId];
});
}
else {
//[self setRunLoopStarted:FALSE];
dispatch_async(_serialQueue, ^{
[self dispatchSession:sessionId];
});
NSLog(#"Adding block to the dispatch queue is complete");
}
}
uploadSession:#"session" is being called from view controllers.
The problem that I am facing is sometimes the code present in dispatchSession is called, but sometimes block is not called.
I only observe the log print statement after the block is printed.
Can any one of you explain the reason behind this?

This is weird code. Try this instead
-(void)uploadSession:(NSString *)sessionId
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_serialQueue = dispatch_queue_create("sessionUploadQueue", NULL);
});
dispatch_async(_serialQueue, ^{
[self dispatchSession:sessionId];
});
}

Related

Wait for URLConnection block to finish

I'm creating a REST client class for my iPad app. So I created a BOOL method which does the login using an NSURLConnection subclass I created earlier.
This JWURLConnection has block type properties for the finishLoading and failWithError operations.
The Problem is that the URL connection most likely finishes (or fails) AFTER this method is completely executed. A cannot use an extra method to use performSelector:waitUntilDone: too because I have to wait for the connection.
Now I tried using plain C semaphores and an extra thread (so that the semaphore blocks only the RESTClient thread, not the URLConnections one), but I had no success; the method started waiting but the whole connection stuff was frozen, thus there where no NSLogs from the connection.
The JWURLConnection starts it's own thread by itself within the -start method:
- (void)start { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [super start]; }); }
Here is the code I tried it with (using semaphores):
- (BOOL)loginWithUsername:(NSString *)uName ansPassword:(NSString *)pWord {
__block BOOL loginSucceeded = NO;
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
JWURLConnection *connection = [JWURLConnection connectionWithPOSTRequestToURL:POSTData:];
[connection setFinished^(NSData *data) {
// validate server response and set login variable
loginSucceeded = YES;
dispatch_semaphore_signal(sema);
}];
[connection setFailed:^(NSError *error) {
loginSucceeded = NO;
NSLog(#"Login failed: %#", [error description]);
dispatch_semaphore_signal(sema);
}];
[connection start];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
// do some more stuff like error handling / reporting here
return loginSucceeded;
}
I hope you can lead my the right direction...
The JWURLConnection starts it's own thread by itself within the -start method:
- (void)start { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [super start]; }); }
You need to ensure that a NSURLConnection's delegate methods will be scheduled on a NSRunLoop or a NSOperationQueue. While the start method could actually take care of this - the given code and your comment indicate it does not ;) In short, dispatch_async does not guarantee that the underlaying thread has a run loop and a dispatch queue does not even guarantee that the underlaying thread is always the same.
The docs show how to schedule a connection.
I would suggest to schedule the connection on the main thread, and change this to a NSOperationQueue when required.
Your loginWithUsername:andPassword: method will simply return immediately since you call/invoke an asynchronous function/method.
Employing asynchronous patterns is kinda "infectious". Once you started using asynchronous programming style, you cant get "rid of" it unless you use synchronization primitives that block the current thread. I would suggest to keep the async style:
- (void) loginWithUsername:(NSString *)uName
andPassword:(NSString *)pWord
completion:(void(^)(id result))onCompletion;
And later:
[self loginWithUsername:#"Me" andPassword:#"secret" completion:^(id result) {
if ([result != [isKindOfError class]]) {
[self fetchImagesWithURL:url completion: ^(id result) {
...
}];
}
}];

GCD flow how to write

I am trying to make screen shot of avplayer when video start playing so i need to run this code in fast in background so it will not block main thread and other controls run fast simultaneous,trying to run that code GCD format i am not able to run please help me to do that it stops at where i add into my array(in array i am adding UIImage Object)...
if (isCaptureScreenStart)
{
if (CMTimeGetSeconds([avPlayer currentTime])>0)
{
if (avFramesArray!=nil)
{
queue = dispatch_queue_create("array", NULL);
dispatch_sync(queue, ^{
[avFramesArray addObject:[self screenshotFromPlayer:avPlayer maximumSize:avPlayerLayer.frame.size :CMTimeGetSeconds([avPlayer currentTime])]];//stop at this line
NSLog(#"count:%d",[avFramesArray count]);
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Frame are created:%d",[avFramesArray count]);
if ([avFramesArray count]==0)
{
NSLog(#"Frame are over");
}
});
});
}
}
}
dispatch_release(queue);
Edit:
I think i need to use dispatch_group_async this block now..please give some guideline that how to use:
if (isCaptureScreenStart)
{
if (CMTimeGetSeconds([avPlayer currentTime])>0)
{
if (avFramesArray!=nil) {
dispatch_group_async(serial_group1, serial_dispatch_queue1, ^{
[avFramesArray addObject:[self screenshotFromPlayer:avPlayer maximumSize:avPlayerLayer.frame.size :CMTimeGetSeconds([avPlayer currentTime])]];
});
}
}
dispatch_group_notify(serial_group1, serial_dispatch_queue1, ^{
NSLog(#"task competed");
});
}
Now I am using this block but above execution is contentious running and if i use dispatch_suspend(serial_dispatch_queue1); its stop but again i need to start block execution then what i need to use i have also try with dispatch_resume(serial_dispatch_queue1); again load but system show me crash
dispatch_release(queue); don't do it there, the dispatch queue that you are calling its going to a backThread, so wat is happening is :-
your queue is getting released before the block of code executes.
since your queue looks like an ivar, release it in dealloc. Rest, your code looks fine ..put a breakpoint inside and check if the block is executing.
EDIT
I dont understand, what u are trying to achieve by suspending the queue, there is no need to do it. You dont need to check whether the block has finished executing. The block will finish and then call the dispatch_async , get the main queue and update the UI from there.
Now, when you are creating the queue, create it lazily in your method. take the queue as an ivar in header file:
#interface YourFileController : UIViewController {
dispatch_queue_t queue;
}
Then in your method modify it as such:
if (isCaptureScreenStart)
{
if (CMTimeGetSeconds([avPlayer currentTime])>0)
{
if (avFramesArray!=nil)
{
if (!queue)
queue = dispatch_queue_create("array", DISPATCH_QUEUE_SERIAL);
dispatch_sync(queue, ^{
[avFramesArray addObject:[self screenshotFromPlayer:avPlayer maximumSize:avPlayerLayer.frame.size :CMTimeGetSeconds([avPlayer currentTime])]];//stop at this line
NSLog(#"count:%d",[avFramesArray count]);
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Frame are created:%d",[avFramesArray count]);
if ([avFramesArray count]==0)
{
NSLog(#"Frame are over");
}
});
});
}
}
}
NOTE : DISPATCH_QUEUE_SERIAL creates a serial queue, meaning all the blocks submitted to it will execute serially in First in First Out order. Once all the blocks submitted get executed, the queue stays ;) ..submit another block to it and it executes the block :D
this represents one whole block:-
[avFramesArray addObject:[self screenshotFromPlayer:avPlayer maximumSize:avPlayerLayer.frame.size :CMTimeGetSeconds([avPlayer currentTime])]];//stop at this line
NSLog(#"count:%d",[avFramesArray count]);
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Frame are created:%d",[avFramesArray count]);
if ([avFramesArray count]==0)
{
NSLog(#"Frame are over");
}
});

Make sure function runs on main thread only

How can I make sure that my function is run only on the main thread? It updates UI elements.
Is a function like this considered 'bad'?
-(void)updateSomethingOnMainThread {
if ( ![[NSThread currentThread] isEqual:[NSThread mainThread]] )
[self performSelectorOnMainThread:_cmd withObject:nil waitUntilDone:NO];
else {
// Do stuff on main thread
}
}
I wrote it like this to avoid having a second function, initially I had it like this:
-(void)updateSomethingOnMainThread_real {
// Do stuff on main thread
}
-(void)updateSomethingOnMainThread {
[self performSelectorOnMainThread:#selector(updateSomethingOnMainThread_real) withObject:nil waitUntilDone:NO];
}
As an alternative to ayoy's method-based GCD implementation for guaranteeing execution on the main thread, I use the following GCD-based function in my code (drawn from another answer of mine):
void runOnMainThreadWithoutDeadlocking(void (^block)(void))
{
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}
}
You can then use this helper function anywhere in your code:
runOnMainThreadWithoutDeadlocking(^{
// Do stuff that needs to be on the main thread
});
This guarantees that the actions taken in the enclosed block will always run on the main thread, no matter which thread calls this. It adds little code and is fairly explicit as to which code needs to be run on the main thread.
This is fine. You can also use GCD to execute code on the main thread.
Checkout this SO post.
GCD to perform task in main thread
I wrote this simple #define which I've been using with great success:
#define ensureInMainThread(); if (!NSThread.isMainThread) { [self performSelectorOnMainThread:_cmd withObject:nil waitUntilDone:NO]; return; }
That way your method, assuming it's parameterless, looks like this
- (void) updateTheThings {
ensureInMainThread();
[self.dog setTailWag:YES];
// etc...
Alternatively, you can use Grand Central Dispatch API, but it's not very handy:
-(void)updateSomethingOnMainThread {
void (^doStuff)(void) = ^{
// stuff to be done
};
// this check avoids possible deadlock resulting from
// calling dispatch_sync() on the same queue as current one
dispatch_queue_t mainQueue = dispatch_get_main_queue();
if (mainQueue == dispatch_get_current_queue()) {
// execute code in place
doStuff();
} else {
// dispatch doStuff() to main queue
dispatch_sync(mainQueue, doStuff);
}
}
otherwise, if synchronous call isn't needed, you can call dispatch_async() which is much simpler:
-(void)updateSomethingOnMainThread {
dispatch_async(dispatch_get_main_queue(), ^{
// do stuff
});
}

GCD, Threads, Program Flow and UI Updating

I'm having a hard time figuring out how to put this all together.
I have a puzzle solving app on the mac.
You enter the puzzle, press a button, and while it's trying to find the number of solutions,
min moves and such I would like to keep the UI updated.
Then once it's finished calculating, re-enable the button and change the title.
Below is some sample code from the button selector, and the solving function:
( Please keep in mind I copy/paste from Xcode so there might be some missing {} or
some other typos.. but it should give you an idea what I'm trying to do.
Basicly, user presses a button, that button is ENABLED=NO, Function called to calculate puzzle. While it's calculating, keep the UI Labels updated with moves/solution data.
Then once it's finished calculating the puzzle, Button is ENABLED=YES;
Called when button is pressed:
- (void) solvePuzzle:(id)sender{
solveButton.enabled = NO;
solveButton.title = #"Working . . . .";
// I've tried using this as a Background thread, but I can't get the code to waitTilDone before continuing and changing the button state.
[self performSelectorInBackground:#selector(createTreeFromNode:) withObject:rootNode];
// I've tried to use GCD but similar issue and can't get UI updated.
//dispatch_queue_t queue = dispatch_queue_create("com.gamesbychris.createTree", 0);
//dispatch_sync(queue, ^{[self createTreeFromNode:rootNode];});
}
// Need to wait here until createTreeFromNode is finished.
solveButton.enabled=YES;
if (numSolutions == 0) {
solveButton.title = #"Not Solvable";
} else {
solveButton.title = #"Solve Puzzle";
}
}
Needs to run in background so UI can be updated:
-(void)createTreeFromNode:(TreeNode *)node
{
// Tried using GCD
dispatch_queue_t main_queue = dispatch_get_main_queue();
...Create Tree Node and find Children Code...
if (!solutionFound){
// Solution not found yet so check other children by recursion.
[self createTreeFromNode:newChild];
} else {
// Solution found.
numSolutions ++;
if (maxMoves < newChild.numberOfMoves) {
maxMoves = newChild.numberOfMoves;
}
if (minMoves < 1 || minMoves > newChild.numberOfMoves) {
solutionNode = newChild;
minMoves = newChild.numberOfMoves;
// Update UI on main Thread
dispatch_async(main_queue, ^{
minMovesLabel.stringValue = [NSString stringWithFormat:#"%d",minMoves];
numSolutionsLabel.stringValue = [NSString stringWithFormat:#"%d",numSolutions];
maxMovesLabel.stringValue = [NSString stringWithFormat:#"%d",maxMoves];
});
}
GCD and performSelectorInBackground samples below. But first, let's look at your code.
You cannot wait where you want to in the code above.
Here's the code you had. Where you say wait in the comment is incorrect. See where I added NO.
- (void) solvePuzzle:(id)sender{
solveButton.enabled = NO;
solveButton.title = #"Working . . . .";
// I've tried using this as a Background thread, but I can't get the code to waitTilDone before continuing and changing the button state.
[self performSelectorInBackground:#selector(createTreeFromNode:) withObject:rootNode];
// NO - do not wait or enable here.
// Need to wait here until createTreeFromNode is finished.
solveButton.enabled=YES;
}
A UI message loop is running on the main thread which keeps the UI running. solvePuzzle is getting called on the main thread so you can't wait - it will block the UI. It also can't set the button back to enabled - the work hasn't been done yet.
It is the worker function's job on the background thread to do the work and then when it's done to then update the UI. But you cannot update the UI from a background thread. If you're not using blocks and using performSelectInBackground, then when you're done, call performSelectorOnMainThread which calls a selector to update your UI.
performSelectorInBackground Sample:
In this snippet, I have a button which invokes the long running work, a status label, and I added a slider to show I can move the slider while the bg work is done.
// on click of button
- (IBAction)doWork:(id)sender
{
[[self feedbackLabel] setText:#"Working ..."];
[[self doWorkButton] setEnabled:NO];
[self performSelectorInBackground:#selector(performLongRunningWork:) withObject:nil];
}
- (void)performLongRunningWork:(id)obj
{
// simulate 5 seconds of work
// I added a slider to the form - I can slide it back and forth during the 5 sec.
sleep(5);
[self performSelectorOnMainThread:#selector(workDone:) withObject:nil waitUntilDone:YES];
}
- (void)workDone:(id)obj
{
[[self feedbackLabel] setText:#"Done ..."];
[[self doWorkButton] setEnabled:YES];
}
GCD Sample:
// on click of button
- (IBAction)doWork:(id)sender
{
[[self feedbackLabel] setText:#"Working ..."];
[[self doWorkButton] setEnabled:NO];
// async queue for bg work
// main queue for updating ui on main thread
dispatch_queue_t queue = dispatch_queue_create("com.sample", 0);
dispatch_queue_t main = dispatch_get_main_queue();
// do the long running work in bg async queue
// within that, call to update UI on main thread.
dispatch_async(queue,
^{
[self performLongRunningWork];
dispatch_async(main, ^{ [self workDone]; });
});
}
- (void)performLongRunningWork
{
// simulate 5 seconds of work
// I added a slider to the form - I can slide it back and forth during the 5 sec.
sleep(5);
}
- (void)workDone
{
[[self feedbackLabel] setText:#"Done ..."];
[[self doWorkButton] setEnabled:YES];
}
dispatch_queue_t backgroundQueue;
backgroundQueue = dispatch_queue_create("com.images.bgqueue", NULL);
- (void)process {
dispatch_async(backgroundQueue, ^(void){
//background task
[self processHtml];
dispatch_async(main, ^{
// UI updates in main queue
[self workDone];
});
});
});
}
By and large, any work to be submitted to a background queue needs to follow this pattern of code:
dispatch_queue_t queue = dispatch_queue_create("com.myappname", 0);
__weak MyClass *weakSelf = self; //must be weak to avoid retain cycle
//Assign async work
dispatch_async(queue,
^{
[weakSelf doWork];
dispatch_async(dispatch_get_main_queue(),
^{
[weakSelf workDone];
});
});
queue = nil; //Using ARC, we nil out. Block always retains the queue.
Never Forget:
1 - queue variable above is a reference counted object, because it is a private queue, not a global one. So it is retained by the block which is executing inside that queue. Until this task is complete, it is not released.
2 - Every queue got its own stack which will be allocated / deallocated as part of recursive operation. You only need to worry about class member variables which are reference counted (strong, retain etc.) which are accessed as part of doWork above.
3 - While accessing those reference counted vars inside background queue operation, you need to make them thread-safe, depending on use cases in your app. Examples include writes to objects such as strings, arrays etc. Those writes should be encapsulated inside #synchronized keyword to ensure thread-safe access.
#synchronized ensures no another thread can get access to the resource it protects, during the time the block it encapsulates gets executed.
#synchronized(myMutableArray)
{
//operation
}
In the above code block, no alterations are allowed to myMutableArray inside the #synchronized block by any other thread.

prevent multiple dispatch_queue_create from being created in viewDidLoad

have a view that loads and a serial dispatch queue that is created, loads a ton of stuff in the background and works great. Problem is when I navigate back and forth to that view a new queue is created again and then I have multiple things doing the exact same work.
- (void)viewDidLoad {
dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
dispatch_async(myQueue, ^{
//function call to a helper outside the scope of this view
});
}
How do I prevent this from happening?
EDIT:
creating my own queue was not necessary so I change my code - same problem still exists.
Put it in the initialization code or move myQueue to an instance variable and then check for its existence.
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
{
dispatch_queue_t myQueue = dispatch_queue_create("com.mydomain.myapp.longrunningfunction", NULL);
dispatch_async(myQueue, ^{
//function call to a helper outside the scope of this view
});
dispatch_async(myQueue, ^{
dispatch_async(dispatch_get_main_queue(), ^{
dispatch_release(myQueue);
});
});
}
return self;
}
Or...
- (void)viewDidLoad {
if(!_myQueue)
{
_myQueue = dispatch_queue_create("com.mydomain.myapp.longrunningfunction", NULL);
dispatch_async(_myQueue, ^{
//function call to a helper outside the scope of this view
});
dispatch_async(_myQueue, ^{
dispatch_async(dispatch_get_main_queue(), ^{
dispatch_release(_myQueue);
});
});
}
}
And if you only want it to run once during a single run of the application you can use dispatch_once
So here is a way to achieve what I really desire, prevent my dispatched queued items from running when my view is popped from the navigation stack:
I simple wrap this code around my code that is running in my dispatched queue:
-(void) myMethod {
if (self.view.window) {
//my code
}
}
This came from watching the Blocks & Multithreading video here by Stanford:
http://itunes.apple.com/us/itunes-u/developing-apps-for-ios-hd/id395605774
great video, helped lot.
If using a storyboard put your initialization in here:
-(void)awakeFromNib{}