问题描述
我在iPad上有一个功能,我需要按顺序运行3个步骤,比如task1,task2,task3。 Task2需要从服务器加载一些数据。所以我需要将task2放入一个单独的后台线程中。
I have a function on iPad that I need to run 3 steps in sequence, let's say task1, task2, task3. Task2 needs load some data from server. So I need to put task2 into a separate background thread.
- (IBAction)dbSizeButton:(id)sender {
//Task1......
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
//Task2 .....which go to server and download some stuff and update database.
dispatch_sync(dispatch_get_main_queue(), ^{
//Task3, continue to work on UI
});
});
}
但看起来正在发生的事情是应用程序经常在Task2启动时被杀死。我不确定为什么。我可以看到Task2确实在一个单独的线程中执行。所以我想知道,如果不是这样做的方式,而不是使用GCD,我可以在Task2的末尾向主线程发送消息或通知,以便我可以启动Task3吗?究竟是怎么做的?
But looks like what is happening is the app often got killed when Task2 starts. I am not sure exactly why. I can see Task2 does execute in a separate thread. So I am wondering, if that is not the way to do it, instead of using GCD, can I at the end of Task2 send a message or a notification to the main thread so I can kick off Task3? How exactly to do that?
推荐答案
问题仅在于您使用 dispatch_sync
,阻止。这就是你被杀的原因。你几乎把它弄好了。你想要的是:
The problem is merely your use of dispatch_sync
, which blocks. That's why you're being killed. You almost had it right. What you want is:
// ... task 1 on main thread
dispatch_async(other_queue, ^{
// ... task 2 in background thread
dispatch_async(dispatch_get_main_queue(), ^{
// ... task 3 on main thread
});
});
这是下线主线程并重新开始的标准模式。这就是它的全部!
That is the standard pattern for getting off the main thread and coming back on. That's all there is to it!
这篇关于如何在Xcode中向主线程发送消息或通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!