gpt4 book ai didi

ios - 获取当前后台操作并处理它

转载 作者:搜寻专家 更新时间:2023-11-01 05:54:23 25 4
gpt4 key购买 nike

我想在后台操作完成时做一些事情,我正在使用以下代码来执行后台操作:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) { () -> Void in
//perform the background operation
})

但是换个角度看,如何获取当前的后台操作并进行处理呢?
非常感谢:)

最佳答案

一般不会“获取当前后台操作”。如果你想在后台操作完成时做一些事情,你通常只是把它放在 block 本身中。例如,如果你想在后台任务完成时更新 UI(在主队列上),你可以这样做:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// perform the background operation

// now do whatever you want when the above is done

dispatch_async(dispatch_get_main_queue(), ^{
// do whatever you want here
});
});

如果您有一系列已分派(dispatch)到后台的 block ,并且您想等待所有 block 完成,您通常会使用分派(dispatch)组:

dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_queue_t notificationQueue = dispatch_get_main_queue();

dispatch_group_async(group, queue, ^{
// do something
});

dispatch_group_async(group, queue, ^{
// do something else
});

dispatch_group_notify(group, notificationQueue, ^{
// whatever you want when the above dispatched blocks finish
});

或者您可以使用操作队列,并为给定操作设置一个 completionBlock,或者创建一个依赖于其他操作的新操作(仅当其他操作完成时才会触发)。

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSOperationQueue *completionQueue = [NSOperationQueue mainQueue];

NSOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
// do something
}];
[queue addOperation:operation1];

NSOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
// do something else
}];
[queue addOperation:operation2];

NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
// whatever you want when the above operations finish
}];
[completionOperation addDependency:operation1];
[completionOperation addDependency:operation2];
[completionQueue addOperation:completionOperation];

显然,上述所有示例都是在 Objective-C 中,但通用模式在 Swift 中也同样适用。

有关异步编程技术的更多信息,请参阅 Concurrency Programming Guide .或引用WWDC 2012 video - Asynchronous Design Patterns with Blocks, GCD, and XPC .

关于ios - 获取当前后台操作并处理它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26724030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com