简体   繁体   English

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

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

This is what I am doing. 这就是我在做什么。

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
    });
});

My problem is the reachability test is being done in the main queue, which often freezes the UI. 我的问题是可及性测试是在主队列中完成的,通常会冻结UI。 I want to run in a background mode. 我想在后台模式下运行。

I want to process the ReachabilityTest in a background mode or in a low priority mode. 我想在后台模式或低优先级模式下处理ReachabilityTest。 But again, my reachability controller does notify user of the current net avaibility, so at some point i will have to use main queue again. 但是,我的可达性控制器确实会通知用户当前的网络可用性,因此在某些时候我将不得不再次使用主队列。

I strongly believe that there must be a better way. 我坚信必须有更好的方法。

This is, however, a correct way. 但是,这是正确的方法。 It doesn't look entirely pretty, but that doesn't mean it's incorrect. 它看起来并不完全漂亮,但这并不意味着它是不正确的。 If you want your code to look 'cleaner' you might wanna take a look at NSThread and work your way through it, but this is a far easier approach. 如果您想让代码看起来更“干净”,则可以看一下NSThreadNSThread进行处理,但这是一种简单得多的方法。

To make it look easier in my project we made a simple class called dispatcher that uses blocks: 为了使它在我的项目中看起来更简单,我们制作了一个简单的类,称为调度程序,它使用块:

+ (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);
}

used like this: 像这样使用:

[Dispatcher dispatchOnBackgroundAsync:^{
    // background thread code

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

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

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