dispatch_async并在原始队列上调用完成处理程序 [英] dispatch_async and calling a completion handler on the original queue
问题描述
我已经看到一些相关的问题,但似乎没有一个答案.我想写一个在后台做一些工作的方法.我需要此方法在用于原始方法调用的同一线程/队列上调用完成回调.
I've seen some related questions but none seem to answer this case. I want to write a method that will do some work in the background. I need this method to call a completion callback on the same thread / queue used for the original method call.
- (void)someMethod:(void (^)(BOOL result))completionHandler {
dispatch_queue_t current_queue = // ???
// some setup code here
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
BOOL ok = // some result
// do some long running processing here
dispatch_async(current_queue, ^{
completionHandler(ok);
});
});
这里需要什么魔咒,以便在与sameMethod
调用相同的队列或线程上调用完成处理程序?我不想承担主线程.当然,不使用dispatch_get_current_queue
.
What magic incantation is needed here so the completion handler is called on the same queue or thread as the call to sameMethod
? I don't want to assume the main thread. And of course dispatch_get_current_queue
is not to be used.
推荐答案
如果查看Apple文档,似乎有两种模式.
If you look through the Apple docs, there appear to be two patterns.
如果假定完成处理程序将在主线程上运行,则无需提供任何队列.一个示例是UIView
的animations
方法:
If it is assumed that the completion handler is to be run on the main thread, then no queue needs to be provided. An example would be UIView
's animations
methods:
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion
否则,API通常会要求调用者提供一个队列:
Otherwise, the API usually asks the caller to provide a queue:
[foo doSomethingWithCompletion:completion targetQueue:yourQueue];
我的建议是遵循这种模式.如果尚不清楚应调用完成处理程序的队列,则调用者应明确将其作为参数提供.
My suggestion is to follow this pattern. If it is unclear which queue the completion handler should be called, the caller should supply it explicitly as a parameter.
这篇关于dispatch_async并在原始队列上调用完成处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!