3

对于互联网检查,我编写了以下代码行。

bool isAvailable = NetworkInterface.GetIsNetworkAvailable();
             if (isAvailable == true)
             {
}

如果网络也不可用,上述行总是返回 true。请告诉我如何检查互联网连接?

4

4 回答 4

2

检查NetworkInterfaceType。如果 Internet 可用,则它应该不是None

return (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType 
!= Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None);

vjsrinath 的参考答案https ://stackoverflow.com/questions/8341169/how-to-check-internetconnection-in-wp7

希望这可以帮助。

于 2012-06-22T11:10:21.740 回答
1

你也可以试试,

bool isAvailable = Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkAvailable;
于 2012-06-22T11:14:55.233 回答
0

NetworkInterface.NetworkInterfaceType入 UI 线程是“危险的”,因为它是一个阻塞调用!此调用可能需要长达 20 秒...

使用以下方法进行非阻塞调用:

public static void IsConnected(Action<bool> completed)
{
    ThreadPool.QueueUserWorkItem(o =>
    {
        var type = NetworkInterface.NetworkInterfaceType;
        completed(type != NetworkInterfaceType.None);
    });
}

请参阅https://xp-dev.com/svn/mytoolkit/MyToolkit.Wp8/Networking/NetworkState.cs来自我的项目页面

如果您想更改completed操作中的 UI,您必须在 UI 线程中运行逻辑。例如:

NetworkState.IsConnected(connected => {
    if (connected)
    {
        Deployment.Current.Dispatcher.BeginInvoke(delegate { 
            // TODO add your UI logic
        });
    }
});

如果您需要大量连接检查,请查看NetworkStateTracker我的项目:

https://xp-dev.com/svn/mytoolkit/MyToolkit.Wp8/Networking/NetworkStateTracker.cs

于 2012-06-23T14:20:10.420 回答
0
     Always check this in a thread, it takes some time        
    internal static bool IsNetworkAvailable()
    {
        bool _bhasNetworkConnection = false;
        try
        {
            _bhasNetworkConnection = (NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None);
        }
        catch
        {
            _bhasNetworkConnection = false;
        }

        return _bhasNetworkConnection;
    }
于 2012-06-22T11:51:40.557 回答