3

在我的 iOS 应用程序中,我在后台线程上运行计算密集型任务,如下所示:

// f is called on the main thread
- (void) f {
    [self performSelectorInBackground:@selector(doCalcs) withObject:nil]; 
}

- (void) doCalcs {
    int r = expensiveFunction();
    [self performSelectorOnMainThread:@selector(displayResults:) withObject:@(r) waitUntilDone:NO];
}

如何使用 GCD 运行昂贵的计算,使其不会阻塞主线程?

我已经查看dispatch_async了 GCD 队列选择的一些选项,但我对 GCD 太陌生了,感觉我理解它不够。

4

1 回答 1

10

您像建议的那样使用 dispatch_async 。

例如:

    // Create a Grand Central Dispatch (GCD) queue to process data in a background thread.
dispatch_queue_t myprocess_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

// Start the thread 

dispatch_async(myprocess_queue, ^{
    // place your calculation code here that you want run in the background thread.

    // all the UI work is done in the main thread, so if you need to update the UI, you will need to create another dispatch_async, this time on the main queue.
    dispatch_async(dispatch_get_main_queue(), ^{

    // Any UI update code goes here like progress bars

    });  // end of main queue code block
}); // end of your big process.
// finally close the dispatch queue
dispatch_release(myprocess_queue);

这就是它的一般要点,希望对您有所帮助。

于 2013-08-20T20:53:00.910 回答