GCD to perform task in main thread - objective-c

I have a callback which might come from any thread. When I get this callback, then I would like to perform a certain task on the main thread.
Do I need to check whether I already am on the main thread - or is there any penalty by not performing this check befora calling the code below?
dispatch_async(dispatch_get_main_queue(), ^{
// do work here
});

No, you do not need to check whether you’re already on the main thread. By dispatching the block to the main queue, you’re just scheduling the block to be executed serially on the main thread, which happens when the corresponding run loop is run.
If you already are on the main thread, the behaviour is the same: the block is scheduled, and executed when the run loop of the main thread is run.

For the asynchronous dispatch case you describe above, you shouldn't need to check if you're on the main thread. As Bavarious indicates, this will simply be queued up to be run on the main thread.
However, if you attempt to do the above using a dispatch_sync() and your callback is on the main thread, your application will deadlock at that point. I describe this in my answer here, because this behavior surprised me when moving some code from -performSelectorOnMainThread:. As I mention there, I created a helper function:
void runOnMainQueueWithoutDeadlocking(void (^block)(void))
{
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}
}
which will run a block synchronously on the main thread if the method you're in isn't currently on the main thread, and just executes the block inline if it is. You can employ syntax like the following to use this:
runOnMainQueueWithoutDeadlocking(^{
//Do stuff
});

As the other answers mentioned, dispatch_async from the main thread is fine.
However, depending on your use case, there is a side effect that you may consider a disadvantage: since the block is scheduled on a queue, it won't execute until control goes back to the run loop, which will have the effect of delaying your block's execution.
For example,
NSLog(#"before dispatch async");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"inside dispatch async block main thread from main thread");
});
NSLog(#"after dispatch async");
Will print out:
before dispatch async
after dispatch async
inside dispatch async block main thread from main thread
For this reason, if you were expecting the block to execute in-between the outer NSLog's, dispatch_async would not help you.

No you don't need to check if you're in the main thread. Here is how you can do this in Swift:
runThisInMainThread { () -> Void in
runThisInMainThread { () -> Void in
// No problem
}
}
func runThisInMainThread(block: dispatch_block_t) {
dispatch_async(dispatch_get_main_queue(), block)
}
Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions

Related

ObjectiveC - Avoiding deadlock while synchronous dispatch to main queue from background

Recently I came to a point where I needed some block of code to execute always on the main thread synchronously. This block can be called from any thread. I solved this problem with the code that was already suggested in this SO answer by #Brad Larson
As the comments to this answer it is evident that the deadlock can occur, but I got into the deadlock very very easily. Please have a look at this code.
-(IBAction) buttonClicked
{
// Dispatch on the global concurrent queue async.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSString* data = [self getTheString];
NSLog(#"From Background Thread: %#", data);
};
// Dispatch on the main queue async.
dispatch_async(dispatch_get_main_queue(), ^{
NSString* data = [self getTheString];
NSLog(#"From Main Thread: %#", data);
};
}
// This method can be called from any thread so synchronize it.
// Also the code that sets the string variable based on some logic need to execute on main thread.
-(NSString*) getTheString
{
__block NSString* data = nil;
#synchronized(self)
{
// Have some code here that need to be synchronized between threads.
// .......
//
// Create a block to be executed on the main thread.
void (^blockToBeRunOnMainThread)(void) = ^{
// This is just a sample.
// Determining the actual string value can be more complex.
data = #"Tarun";
};
[self dispatchOnMainThreadSynchronously:blockToBeRunOnMainThread];
}
}
- (void) dispatchOnMainThreadSynchronously:(void(^)(void))block
{
if([NSThread isMainThread])
{
if (block)
{
block();
}
}
else
{
dispatch_sync(dispatch_get_main_queue(), ^{
if (block)
{
block();
}
});
}
}
In this piece of code there are two simultaneous asynchronous requests to function getTheString (Assume you have no control over the buttonClicked method and how it calls getTheString api) . Suppose the request from global queue comes first and it is trying to run the block on the main thread synchronously, till that time background thread in waiting for main thread to execute the block synchronously, at the same time request from main queue comes and trying the acquire the lock from background thread, but as background thread in not complete main thread waiting for background thread to complete. Here we have a deadlock on main thread as main thread waiting for background thread to finish, and background thread is waiting for main thread to execute block.
If I remove the #synchronize statement everything works fine as expected. May be I don't need a #synchronize statement here but in same case you may need to have this. Or it can even happen from some other parts of the code.
I tried to search the whole net for the solution and also tried dispatch_semaphore but couldn't solve the issue. May be I am just not doing things the right way.
I assume this is classic problem of deadlock and faced by developers again and again, and probably have solved it to some extent. Can anyone help with this, or point me to right direction?
I would create a synchronous queue (NSOperationQueue would be simplest) and submit the block to be run on the main thread to that queue. The queue would dispatch the blocks in the order received, maintaining the ordering you desire. At the same time, it disassociates the synchronicity between calling the getTheString method and the dispatch to the main thread.

GCD - How to wait on the main thread for an async callback that is performed on the main queue

I want to perform 2 blocks one after the other , where each on there own are performed asynchronously.
For instance
[someMethodWithCompletionHandler:^() {
// do something in the completion handler
}];
[anotherMethodWithCompletionHandler:^ {
// do something else in the completion handler after the first method completes
}];
Now, I need 'anotherMethodWithCompletionHandler' to happen after 'someMethodWithCompletionHandler' completes (including its completion handler)
regularly I would create a dispatch_group and wait in between the 2 methods (I can not nest the 2 methods in the other completion handler because it would require a lot of code to be moved)
But the problem is that the first completion handler block is called in the main thread (by the method itself calling the block in the main thread) so I can not effectively create a dispatch_group blocking the main thread.
So the thread state looks something like this
// main thread here
[self doFirstPortionOfWork];
// main thread here
[self doSecondPortionOfWork];
-(void)doFirstPortionOfWork
{
.. a lot of stuff happening
[someMethodWithCompletionHandler:^{
// this is the main thread
}];
// would like to block the return here until the completion handler finishes
}
-(void)doSecondPortionOfWork
{
... a lot of work here
[anotherMethodWithCompletionHandler^{
// this is also called into the main thread
}];
// would like to block the return here until the completion handler finishes
}
So how could I do this with out resorting to a lot of nested methods and be able to block the main thread until all complete?
Main Thread is the same as Main Queue
It is not possible to wait on Main Thread for future work in Main Thread. You are blocking the future work.
You can do it like this:
[someMethodWithCompletionHandler:^() {
// do something in the completion handler
[anotherMethodWithCompletionHandler:^ {
// do something else in the completion handler after the first method completes
}];
}];

Waiting for asynchronous threads in objective-c

I am trying to wait for asynchronous threads in objective-c without blocking the UI thread (it is an app).
I have the following code:
-(void)MainUIThread
{
[exporter exportAsynchronouslyWithCompletionHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
[self exportDidFinish:exporter];
//wait here without blocking
});
}];
}
In C# I would use async and await, can I easily achieve this in objective-c?
[exporter exportAsynchronouslyWithCompletionHandler:^{
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
[self exportDidFinish:exporter]; // Its non blocking process
dispatch_async(dispatch_get_main_queue(), ^(void){
//Update your UI.
});
}];
Try above snippet.
You calling [self exportDidFinish:exporter] method on main thread that why it block your UI. I suppose exportDidFinish method have just a business logic then post that logic calculation in background thread using dispatch_get_global_queue then get it back on main thread using dispatch_get_main_queue().
What makes you think that you should wait for an asynchronous operation to finish? That's the whole point of asynchronous operation, you don't wait for it!
You called exportAsynchronouslyWithCompletionHandler and gave it a block. I don't know that method, but I assume it will do things asynchronously, and when it is finished it will call the block that you give it. The call to exportAsynchronouslyWithCompletionHandler will return very quickly, as soon as the method has set up its asynchronous operation.
That block dispatches another block calling "exportDidFinish:exporter" on the main thread, then it returns (with no reason to wait), then all the asynchronous code in exportAsynchronouslyWithCompletionHandler is finished.
All we have now is one block dispatched to the main queue. As soon as the run loop is idle, that block is executed on the main thread. The commented line that you added "// Wait here" is pointless. exportDidFinish:exporter will be called on the main thread when it's time to be called, and then we are done.

dispatch_sync on main queue hangs in unit test

I was having some trouble unit testing some grand central dispatch code with the built in Xcode unit testing framework, SenTestingKit. I managed to boil my problem done to this. I have a unit test that builds a block and tries to execute it on the main thread. However, the block is never actually executed, so the test hangs because it's a synchronous dispatch.
- (void)testSample {
dispatch_sync(dispatch_get_main_queue(), ^(void) {
NSLog(#"on main thread!");
});
STFail(#"FAIL!");
}
What is it about the testing environment that causes this to hang?
dispatch_sync runs a block on a given queue and waits for it to complete. In this case, the queue is the main dispatch queue. The main queue runs all its operations on the main thread, in FIFO (first-in-first-out) order. That means that whenever you call dispatch_sync, your new block will be put at the end of the line, and won't run until everything else before it in the queue is done.
The problem here is that the block you just enqueued is at the end of the line waiting to run on the main thread—while the testSample method is currently running on the main thread. The block at the end of the queue can't get access to the main thread until the current method (itself) finishes using the main thread. However dispatch_sync means Submits a block object for execution on a dispatch queue and waits until that block completes.
The problem in your code is that no matter whether you use dispatch_sync or dispatch_async , STFail() will always be called, causing your test to fail.
More importantly, as BJ Homer's explained, if you need to run something synchronously in the main queue, you must make sure you are not in the main queue or a dead-lock will happen. If you are in the main queue you can simply run the block as a regular function.
Hope this helps:
- (void)testSample {
__block BOOL didRunBlock = NO;
void (^yourBlock)(void) = ^(void) {
NSLog(#"on main queue!");
// Probably you want to do more checks here...
didRunBlock = YES;
};
// 2012/12/05 Note: dispatch_get_current_queue() function has been
// deprecated starting in iOS6 and OSX10.8. Docs clearly state they
// should be used only for debugging/testing. Luckily this is our case :)
dispatch_queue_t currentQueue = dispatch_get_current_queue();
dispatch_queue_t mainQueue = dispatch_get_main_queue();
if (currentQueue == mainQueue) {
blockInTheMainThread();
} else {
dispatch_sync(mainQueue, yourBlock);
}
STAssertEquals(YES, didRunBlock, #"FAIL!");
}
If you are on the main queue and synchronously wait for the main queue to be available you will indeed wait a long time. You should test to make sure you are not already on the main thread.
Will you ever get out of house if you must wait for yourself to get out house first? You guessed right! No! :]
Basically if:
You are on FooQueue. (doesn't have to be main_queue)
You call the method using sync ie in a serial way and want to execute on FooQueue.
It will never happen for same reason that you will never get out of house!
It won't ever get dispatched because it's waiting for itself to get off the queue!
To follow up, since
dispatch_get_current_queue()
is now deprecated, you can use
[NSThread isMainThread]
to see if you are on the main thread.
So, using the other answer above, you could do:
- (void)testSample
{
BOOL __block didRunBlock = NO;
void (^yourBlock)(void) = ^(void) {
NSLog(#"on main queue!");
didRunBlock = YES;
};
if ([NSThread isMainThread])
yourBlock();
else
dispatch_sync(dispatch_get_main_queue(), yourBlock);
STAssertEquals(YES, didRunBlock, #"FAIL!");
}

How to update UI in a task completion block?

In my application, I let a progress indicator starts animation before I send a HTTP request.
The completion handler is defined in a block. After I get the response data, I hide the progress indicator from inside the block. My question is, as I know, UI updates must be performed in the main thread. How can I make sure it?
If I define a method in the window controller which updates UI, and let the block calls the method instead of updating UI directly, is it a solution?
Also, if your app targets iOS >= 4 you can use Grand Central Dispatch:
dispatch_async(dispatch_get_main_queue(), ^{
// This block will be executed asynchronously on the main thread.
});
This is useful when your custom logic cannot easily be expressed with the single selector and object arguments that the performSelect… methods take.
To execute a block synchronously, use dispatch_sync() – but make sure you’re not currently executing on the main queue or GCD will deadlock.
__block NSInteger alertResult; // The __block modifier makes alertResult writable
// from a referencing block.
void (^ getResponse)() = ^{
NSAlert *alert = …;
alertResult = [NSAlert runModal];
};
if ([NSThread isMainThread]) {
// We're currently executing on the main thread.
// We can execute the block directly.
getResponse();
} else {
dispatch_sync(dispatch_get_main_queue(), getResponse);
}
// Check the user response.
if (alertResult == …) {
…
}
You probably misunderstood something. Using blocks doesn't mean that your code is running in a background thread. There are many plugins that work asynchronously (in another thread) and use blocks.
There are a few options to solve your problem.
You can check if your code is running in the main thread my using [NSThread isMainThread]. That helps you to make sure that you're not in the background.
You can also perform actions in the main or background by using performSelectorInMainThread:SEL or performSelectorInBackground:SEL.
The app immediately crashes when you're trying to call the UI from a bakcground thread so it's quite easy to find a bug.