问题描述
到现在为止,只发生过一次.
Till now, happened just once.
我使用第三方库,它调用以下函数:
I use a third-party library, and it call the function below:
- (BOOL) isReachableViaWiFi {
NSAssert(reachabilityRef, @"isReachableViaWiFi called with NULL reachabilityRef");
SCNetworkReachabilityFlags flags = 0;
NetworkStatus status = NotReachable;
if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) {
status = [self networkStatusForFlags: flags];
return (ReachableViaWiFi == status);
}
return NO;
} // isReachableViaWiFi
当我发现UI停止时,我暂停了程序执行,并且每次它停止在 SCNetworkReachabilityGetFlags
行:
When I find my UI stopped, I paused the program execution, and every time it stops at SCNetworkReachabilityGetFlags
line:
我对此感到困惑.感谢您的提示.
I'm confused about that. Thanks for any tips.
推荐答案
基于您发布的代码,我想说您的问题是您在主线程中同步调用了SCNetworkReachabilityGetFlags.我认为此功能可以在Internet上ping某些东西的可能性很大.如果由于某种原因(您已失去Internet连接)而无法访问它尝试ping的远程主机,您将获得普通的网络超时,这可能会很长(30秒).这次,您将阻塞主线程(具有所有UI).
Basing on the code you've posted I would say that your problem is that you synchronously call to SCNetworkReachabilityGetFlags in main thread. I think there is a big chance that this function pings something on the Internet. If the remote host it tries to ping is not reachable for some reason(you've lost internet connection) you will get ordinary network timeouts which can be really long (30 sec). You will block you main thread (with all the UI) for this time.
因此,解决问题的方法可能是:在另一个队列/线程上调用此函数,然后将结果传递给您的主线程.这样一来,您在等待远程主机响应时就不会阻塞主线程.
So the solution for your problem could be: to call this function on another queue/thread and then pass result to your main thread. By doing this you are not blocking main thread while waiting for some remote host response.
通常,您应避免在主线程上运行任何网络交互代码.
In general you should avoid to run any network interaction code on main thread.
这篇关于主线程在SCNetworkReachabilityGetFlags上被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!