我试图调用一种使用dispatch_async
发送到后台的方法。
它应该是简单的,但是由于某些原因,UI仍然被阻塞,直到方法返回。
以下是我所拥有的:
dispatch_queue_t privateQueue = dispatch_queue_create("com", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(privateQueue, ^
{
__block UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.view.frame];
dispatch_async(dispatch_get_main_queue(), ^
{
imgView = [controllerB startProcess];
controllerC.imageView = imgView;
});
});
在UI再次空闲之前,我仍然需要等待startProcess
返回。
然后我试着把imgView = [controllerB startProcess];
移到dispatch_get_main_queue()
之外
dispatch_async(privateQueue, ^
{
__block UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.view.frame];
imgView = [controllerB startProcess];
dispatch_async(dispatch_get_main_queue(), ^
{
controllerC.imageView = imgView;
});
});
在这种情况下,UI永远不会用imgView
更新,但是UI不会被锁定。
我尝试使用全局队列,但结果是相同的(UI必须等待):
dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
我想我漏掉了一些很明显的东西。无论是那样还是对我来说都是漫长的一天。
编辑:
在[controllerB startProcess];
中
我正在利用:
UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);
UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
我不确定这些方法是否与引起我问题的GCD有关。图像就是.png。
一直在想这件事。我的想法快用完了。使用映像更新UI的唯一方法是将方法调用放在dispatch_get_main_queue()
中,这超出了使用GCD的目的,因为所有UI都会被阻塞,直到映像就绪并返回。
任何建议都将不胜感激。
发布于 2014-02-25 11:40:32
使用第二种方法。修改startProcess以使用完成块,并在完成块中更新imageView。这确保了imageView在startProcess完成后被更新。
发布于 2014-02-25 11:37:01
您的第二个例子--当您尝试在主队列上设置-in时,背景中imageView的异步计算还没有完成,所以它不能显示imageView?在这种情况下,调度组可能会帮助:
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("com.name.queue”, DISPATCH_QUEUE_CONCURRENT);
dispatch_group_async(group, queue, ^{
//Do work
imgView = [controllerB startProcess];
});
dispatch_group_notify(group,queue,^{
//This code runs as soon as the code in the dispatch group is done.
controllerC.imageView = imgView;
});
https://stackoverflow.com/questions/22016905
复制相似问题