Is this Core Graphics code stream safe?

I know that it is safe to draw any thread while I call

UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0); UIGraphicsEndImageContext(); 

in the same topic.

A screenshot using this method takes about 300 ms, which is not bad, but I'm in a tough situation, so I want to do this in the background thread.

That's what I'm doing:

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage * screenshot = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }); 

The only thing in question is the view , which lies on the main thread. Is it safe to call renderInContext on view.layer from the background thread? Or, in general, is a read-only UIKit object from another thread safe?

(And please don’t give me the default β€œUIKit answer is not thread safe.” I already know this. This is a special case (and don’t tell me there are no special cases).)

(The code above works fine, but I'm not sure if this is just a coincidence.)

+7
source share
1 answer

Core Graphics and Core Animation are low-level APIs that are generally thread safe. However, the same access rules still apply: any work should not be accessed by more than one thread at a time, otherwise the drawing will fail and your application will fail. I would be afraid (but not afraid) of UIImage, since UIKit objects are not just not thread safe, they are mostly ticking time bombs in the background thread and will happily dive right off the cliff into Exceptional Earth for no good reason. However, since UIImage is just a CGImage shell, again, most of the drawings are thread safe.

+7
source

All Articles