使用Grand Central Dispatch,如何检查是否已经运行了一个块? [英] Using Grand Central Dispatch, how can I check if there is a block already running?

查看:114
本文介绍了使用Grand Central Dispatch,如何检查是否已经运行了一个块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用GCD从互联网上进行一些后台加载。除了一点点缺陷之外,它的效果很好。在我的应用程序中,我有3个选项卡,当点击任何选项卡时,GCD开始为相应的选项卡执行后台加载。如果用户决定从第一个选项卡转到第二个选项卡(当GCD开始下载第一个选项卡的数据时),然后再次返回第一个选项卡。 GCD将启动另一个后台线程(即使第一个后台线程尚未完成下载数据)。

I'm using GCD to do some background loading from the internet. This works great except for a little flaw. In my app I have 3 tabs and when clicking on any tab the GCD starts to do the background loading for the appropriate tab. If the user decides to go from the first tab to the second tab (when the GCD has started downloaded data for the first tab) and then returns to the first tab again. GCD will start another background thread (even though the first background thread hasn't finished downloaded the data yet).

那么有没有办法检查后台线程当前是否正在运行?因此,如果用户选择非常快速地来回切换标签(由于某种原因),它就不会启动多个后台线程。

So is there a way to check if a background thread is currently running? So that it doesn't start multiple background threads if the user would choose to switch tabs back and forth very quickly (for some reason).

推荐答案

如果要防止两个相同类型的块同时运行,可以使用调度信号量。将信号量设置为1,您可以在关闭块之前检查信号量,并在某些事情仍在运行时保释。在块结束时,您发信号通知信号量以允许提交其他块。

If you wanted to prevent two blocks of the same type from running at the same time, you could use a dispatch semaphore. With a semaphore set to a count of 1, you can check the semaphore before firing off the block and bail if something is still running. At the end of the block, you signal the semaphore to allow other blocks to be submitted.

我在我的一个应用程序中执行此操作以防止多个OpenGL ES帧渲染块一次添加到队列中(如果帧花费的时间超过1/60秒,则会阻止队列中的块的累积)。我在答案此处中描述了一些内容,以下代码:

I do this in one of my applications to prevent more than one OpenGL ES frame rendering block to be added to the queue at once (preventing buildup of blocks in the queue if a frame takes longer than 1/60th of a second to render). I describe some of this in my answer here, using the following code:

if (dispatch_semaphore_wait(frameRenderingSemaphore, DISPATCH_TIME_NOW) != 0)
{
    return;
}

dispatch_async(openGLESContextQueue, ^{

    [EAGLContext setCurrentContext:context];

    // Render here

    dispatch_semaphore_signal(frameRenderingSemaphore);
});

其中 frameRenderingSemaphore 早先创建如下:

frameRenderingSemaphore = dispatch_semaphore_create(1);

如果您为每个标签的下载操作创建类似的信号量,您可以进行检查以确保该标签一次不会排队多个下载。

If you create a similar semaphore for each tab's download operations, you could do a check to make sure that more than one download isn't being queued up at a time for that tab.

这篇关于使用Grand Central Dispatch,如何检查是否已经运行了一个块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆