Re: How to update UI from a background thread
Re: How to update UI from a background thread
- Subject: Re: How to update UI from a background thread
- From: Doug Hill <email@hidden>
- Date: Wed, 21 Sep 2016 10:13:29 -0700
> On Sep 21, 2016, at 10:00 AM, Quincey Morris <email@hidden> wrote:
>
> On Sep 21, 2016, at 09:20 , Dave <email@hidden> wrote:
>>
>> The time consuming method I am calling is in a third party library and it must be called in the main thread.
>
> You cannot update UI on a background thread, so if the library method is blocking the main thread you’re out of luck. The only solution is to get the library author to write proper code.
>
> If the library method is running on the main thread and calling back to a block of your code (which sounds like the case), then it’s safe execute code that issues UI updates, but you likely won’t see the results until later, after your app returns to the main event loop.
>
> If a time-consuming operation *is* running on a background thread, it can dispatch_async a block to the main thread to update the UI, but then you must consider thread safety, if the update is referencing data that’s still being modified as the background thread continues to run.
As Quincy accurately describes, it is well documented you can’t do any UI updates on anything other than the main queue/thread.
https://developer.apple.com/reference/uikit
Which is why your 3rd-party library has this requirement and why CALayer is complaining. So, your UI update needs to be called on the main queue as well.
Sandor’s suggestion to put your UI update code on a block that’s executed sometime later on the main queue SHOULD work as it just delays your code until the queue finishes it’s currently executing tasks. The symptoms you mention sound like a classic deadlock problem. That is, a code block running on the main queue schedules another code block on the main queue, but the original block never completes thus causing the app to hang or the new task never runs. It could well be that there is a bug in the library you’re using that causes it to block the main queue. But it’s probably good to make sure your code is doing the right thing. Perhaps there’s another issue that’s causing the problems you see. Maybe you could provide some code for the case where you use the dispatch_async technique below to accomplish your task and when you don’t and, what happens in each case.
Doug Hill
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden