ios - 使用 GCD 在 block 内赋值

标签 ios objective-c-blocks grand-central-dispatch

我正在执行一个不断从网站寻找更新的线程。应该可以在某些 View 中设置刷新率。

更新线程不断检查更新间隔。但我想避免竞争条件。 (对于 GCD,我什至需要为此担心吗?)

//This variable is used to avoid race conditions, refreshRate is a instance variable
int threadRefreshRate = refreshRate;
BOOL autoRefresh = YES;


dispatch_async(autoUpdateQueue, ^ { 
    while(YES){
        NSLog(@"Runs autoupdate thread");
        dispatch_async(dispatch_get_main_queue(), ^{

            if(autoRefresh){
                [self checkForUpdate];
                //Trying to set thread variable to avoid race condition
                threadRefreshRate = refreshRate;
            }
            else
                NSLog(@"Should not auto refresh");
        });
        sleep(threadRefreshRate);
    }

});

我试图实现这段代码。然而,在一个 block 中赋值“thread”变量是行不通的。

最佳答案

对于您给出的那种代码,我会使用在队列中引发的计时器事件,而不是在代码中进行显式 sleep 。这样你就不必担心比赛条件等。

queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
if (!timer) return;
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), refreshRate * NSEC_PER_SEC, 5 * NSEC_PER_SEC);
dispatch_source_t timer = self.timer;
//initialize self to blockSelf with __block
self.timerAction = ^{
[blockSelf checkForUpdate];
};

dispatch_source_set_event_handler(timer, timerAction);
dispatch_resume(timer);

当autoRefresh设置为NO时,可以通过

取消
dispatch_source_cancel(timer);

关于ios - 使用 GCD 在 block 内赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6121557/

相关文章:

objective-c - NSManagedObjectContext 困惑

ios - 查找两个对象之间更改的属性

ios - 我如何知道 handleOpenURL 响应的文档类型?

objective-c - 在 Block 中释放 View Controller 的位置

objective-c - 在表达式开头使用脱字符 ^ 符号的预处理器宏

ios - 使用 dispatch_sync 作为互斥锁

ios - 正确使用 Grand Central Dispatch 与多个 UIActivityIndi​​catorViews

objective-c - 以编程方式创建 UITextFields

ios - 使用 block 会自动创建新线程吗?

ios - 监视文件更改时打开太多文件