简体   繁体   English

可达性代码阻塞主线程

[英]Reachability code blocking main thread

I'm currently working on an app that requires me to check for reachability. 我目前正在开发一款需要我检查可达性的应用。

Owing to that, I started looking stuff up and found DDG and Apple's code. 由于这个原因,我开始查找东西并找到了DDG和Apple的代码。 I decided to go with Apple's latest reachability code. 我决定使用Apple最新的可访问性代码。

I imported that, and as suggested in Apple's sample, I came up with the following way to register: 我导入了这个,并且按照Apple的样本中的建议,我提出了以下注册方式:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationHandler:) name:kReachabilityChangedNotification object:nil];

    //check for local connection and start notifier
    client = [[Reachability reachabilityForInternetConnection] retain];
    [client startNotifier];

    //check for server connection and start notifier
    server = [[Reachability reachabilityWithHostName:SERVER_HOST_NAME] retain];
    [server startNotifier];

    //check for other server and start notifier
    otherServer = [[Reachability reachabilityWithHostName:OTHER_SERVER_HOST_NAME] retain];
    [otherServer startNotifier];

What I observed when I ran the app was that this code started blocking the UI (blocking the main thread). 我在运行应用程序时观察到的是,此代码开始阻止UI(阻塞主线程)。 I could not interact with other UI elements till the host name was resolved. 在主机名解析之前,我无法与其他UI元素交互。 Now I know that Apple has stated a warning about DNS resolution and making it asynchronous. 现在我知道Apple已经提出了关于DNS解析的警告并使其异步。

My question would be, how do I go ahead and make it asynchronous? 我的问题是,如何继续使其异步?

Do I spawn another thread and keep it running so as to not "release" the Reachability object? 我是否会生成另一个线程并使其保持运行以便不“释放”Reachability对象?

Thanks in advance for your help! 在此先感谢您的帮助! :) :)

Okay. 好的。 Well, I found out what the problem was. 好吧,我发现了问题所在。 >_< > _ <

The code posted above does indeed work asynchronously. 上面发布的代码确实异步工作。

However, the code that I had written under notificationHandler: was making a synchronous call to a service. 但是,我在notificationHandler:下编写的代码正在对服务进行同步调用。 It was written by someone else, owing to which it took me some time to figure out that that was the source of the UI freeze. 它是由其他人编写的,因为我花了一些时间才弄清楚这是UI冻结的来源。 However, problem has been solved. 但问题已经解决了。 I thought I'd write this post so as to give a closure to this question. 我以为我会写这篇文章,以便关闭这个问题。 :) :)

Thanks again! 再次感谢!

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

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