Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatch_get_main_queue() in main thread

I have method which makes UI changes in some cases.

For example:

-(void) myMethod {    if(someExpressionIsTrue) {     // make some UI changes     // ...     // show actionSheet for example   } } 

Sometimes myMethod is called from the mainThread sometimes from some other thread.

Thats is why I want these UI changes to be performed surely in the mainThread.

I changed needed part of myMethod this way:

if(someExpressionIsTrue) {      dispatch_async(dispatch_get_main_queue(), ^{         // make some UI changes         // ...         // show actionSheet for example       }); } 

So the questions:

  • Is it safe and good solution to call dispatch_async(dispatch_get_main_queue() in main thread? Does it influence on performance?
  • Can this problem be solved in the other better way? I know that I can check if it is a main thread using [NSThread isMainThread] method and call dispatch_async only in case of other thread, but it will make me create one more method or block with these UI updates.
like image 491
B.S. Avatar asked Sep 17 '13 10:09

B.S.


People also ask

What is Dispatch_get_main_queue?

A dispatch object that prioritizes the execution of tasks based on their quality-of-service (QoS) level.

Does dispatch_ async create a thread?

When using dispatch_async for a background queue, GCD (Grand Central Dispatch) will ask the kernel for a thread, where the kernel either creates one, picks an idle thread, or waits for one to become idle. These threads, once created, live in the thread pool.

What is DispatchQueue Main?

DispatchQueue. main (the main queue) is a serial queue. sync and async do not determine serialization or currency of a queue, but instead refer to how the task is handled. Synchronous function returns the control on the current queue only after task is finished. It blocks the queue and waits until the task is finished.

What is DispatchQueue main async in Swift?

main. async { doSomething() }` tells GCD to access the main thread and perform the block (doSomething()) asynchronously. One frequent use case for `DispatchQueue. main. async ` in iOS is used when we update UIKit elements after waiting for a network call which happens on a background thread.


1 Answers

There isn't a problem with adding an asynchronous block on the main queue from within the main queue, all it does is run the method later on in the run loop.

What you definitely don't want to do is to call dispatch_sync adding a block to the main queue from within the main queue as you'll end up locking yourself.

like image 160
Abizern Avatar answered Sep 21 '22 12:09

Abizern