Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What queue should delegate code run on

Suppose you have an object that does some work internally on a private dispatch queue (think thread for those not familiar with GCD). This object notifies its delegate at various times throughout the work its doing. It is a bad idea to call the delegate methods from the private queue the code is currently running on, or should they be called on a more well-known queue? If the latter, what queue? It seems like main queue may not always be what you want.

Option A

dispatch_async(private_queue, ^{
    // Do some work...
    [self.delegate tellItWorkWasDone:self];
});

Option B

dispatch_async(private_queue, ^{
    // Do some work...
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self.delegate tellItWorkWasDone:self];
    });
});

Option A has the benefit that its simple, but the drawback that whoever implements the delegate method will be running code on a queue they really shouldn't be on. Option B is probably safer, but main_queue is just an example; how should the two really decide on what queue they should use?

Thanks

like image 630
D.C. Avatar asked Dec 22 '25 17:12

D.C.


1 Answers

I would suggest an option C, actually: have a dedicated queue for delegate callbacks unless the delegate's activity must be completed before your class can continue, in which case use option A.

If UI needs updating, the delegate can dispatch to the main queue itself, don't force that on it.

like image 62
Catfish_Man Avatar answered Dec 24 '25 08:12

Catfish_Man



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!