知道GCD线程是否正在运行

时间:2012-10-31 20:35:23

标签: ios multithreading grand-central-dispatch

在我的iOS应用程序中,我在后台线程中下载了相当多的数据。我需要做的是以某种方式检查用户何时重新打开应用程序,如果此任务仍在运行或已被取消。

如果用户点击主页按钮,然后返回应用程序,则线程将继续,这是好的。但是,如果线程被操作系统拆除,那该怎么办呢。如何在应用程序恢复时知道线程是否正在运行。

谢谢!

一些代码:

// Starts a background thread and also allows it to run in the background if the user exits app
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    UIBackgroundTaskIdentifier bgTask = 0;
    bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask:bgTask];
    }];

// Code here to run in background

// Tell the main thread its done, and also remove itself from background execution
dispatch_async( dispatch_get_main_queue(), ^{
    NSLog(@"Done with background thread");
    [self endBackgroundUpdateTask:bgTask];
});

1 个答案:

答案 0 :(得分:0)

首次关闭任何线程,前景或背景将在您的应用程序进入后台时暂停。当你转换到后台进行完成和清理时,你可以做一些事情来获得少量时间....但是当你的应用离开屏幕时,你肯定会关闭,“背景”线程。

这意味着您的下载将被暂停,您必须优雅地恢复并恢复上次停止的地方。为此,您应该调查iOS提供的技术,以便通知您进入后台并获得一些额外的时间来清理并保存一些可用于恢复的状态。

调查此事:

   beginBackgroundTaskWithExpirationHandler

然后使用backgroundTimeRemaining检查在您获得的额外时间内尝试完成时剩余的时间。当它清楚时,您无法在分配的时间保存状态下完成并设置一个标志,指示您需要在重新启动时继续或重新开始。没有其他方法,因为iOS没有任何方式知道你是否完成了你想要做的事情,这取决于你