繁体   English   中英

如何将操作从主队列转移到后台释放主队列

[英]How to shift operation from main queue to background releasing the main queue

这就是我在做什么。

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);

dispatch_async(queue, ^{
    NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://myurl"]]];
    dispatch_sync(dispatch_get_main_queue(), ^{
        if(!data) {
            // data not recieved or bad data. Initiate reachability test
            // I have built a wrapper for Reachability class called ReachabilityController
            // ReachabilityController also notifies the user for avaibility, UI 

            ReachabilityController *reachability = [[ReachabilityController alloc] init];
            [reachability checkReachability];
            return;
        }
        //update table
    });
});

我的问题是可及性测试是在主队列中完成的,通常会冻结UI。 我想在后台模式下运行。

我想在后台模式或低优先级模式下处理ReachabilityTest。 但是,我的可达性控制器确实会通知用户当前的网络可用性,因此在某些时候我将不得不再次使用主队列。

我坚信必须有更好的方法。

但是,这是正确的方法。 它看起来并不完全漂亮,但这并不意味着它是不正确的。 如果您想让代码看起来更“干净”,则可以看一下NSThreadNSThread进行处理,但这是一种简单得多的方法。

为了使它在我的项目中看起来更简单,我们制作了一个简单的类,称为调度程序,它使用块:

+ (void)dispatchOnBackgroundAsync:(void(^)(void))block {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), block);
}

+ (void)dispatchOnMainAsync:(void(^)(void))block {
    dispatch_async(dispatch_get_main_queue(), block);
}

像这样使用:

[Dispatcher dispatchOnBackgroundAsync:^{
    // background thread code

    [Dispatcher dispatchOnMainAsync:^{
        // main thread code
    }];
}];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM