简体   繁体   中英

Updating UI element without dispatching to the main queue

I have a dispatch_block_t which is passed to another function , and this block will be called when the function finishes the asynchronous task. But the problem is that I don't know which thread this block will be called.

I want to update my UI in the main thread , hence I want to use

dispatch_async(dispatch_get_main_queue(), ^{...})

to update my UI. But I am afraid that this will cause a deadlock if such occasion happens

dispatch_queue_t queue = dispatch_queue_create("my.label", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
    dispatch_async(queue, ^{
        // outer block is waiting for this inner block to complete,
        // inner block won't start before outer block finishes
        // => deadlock
    });

    // this will never be reached
}); 

Is there a way to prevent the deadlock ? Like updating the UI element without using the dispatch queue . Is it possible to create a weak reference to self in order to update the UI?

Try running your example with NSLogs and you'll notice that deadlock doesn't occur. This is due to the fact that using dispatch_async just submits a block to the queue without waiting for it to finish execution (in contrary to dispatch_sync ).

So running this code:

dispatch_queue_t queue = dispatch_queue_create("my.label", DISPATCH_QUEUE_SERIAL);

dispatch_async(queue, ^{
    NSLog(@"1");
    dispatch_async(queue, ^{
        NSLog(@"2");
    });
    NSLog(@"3");
});

Will produce the following log:

Testtt[32153:2250572] 1
Testtt[32153:2250572] 3
Testtt[32153:2250572] 2

Moreover, I'm concerned that using dispatch_async(dispatch_get_main_queue(), ^{...}) here is commonly-used technique which ensures that the consumer gets the result on the main thread (ie consumer doesn't 'care' about threading).

Why, though, you use dispatch_block_t to pass a completion block? In my opinion, it's a bit confusing to use something like that on the consumer side - I would pass an anonymous (without typedef) block or create my own typedef for these simple completion blocks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM