检查互联网连接时出现异常

本文关键字:异常 互联网 连接 检查 | 更新日期: 2023-09-27 18:18:34

我想检查互联网连接在app . example .cs文件,但当我这样做在构造函数它抛出UnhandledException,为什么?这可能吗?当我检查它时,例如mainpage . example .cs,它可以工作。

我代码:

if (NetworkInterface.GetIsNetworkAvailable())
{
    MessageBox.Show("Connected.");
}

调用堆栈:

App.Application_UnhandledException(object sender, System.Windows.ApplicationUnhandledExceptionEventArgs e)
System.Windows.ni.dll!MS.Internal.Error.CallApplicationUEHandler(System.Exception e)
System.Windows.ni.dll!MS.Internal.Error.IsNonRecoverableUserException(System.Exception ex, out uint xresultValue)
System.Windows.ni.dll!System.Windows.Threading.DispatcherOperation.Invoke()
     System.Windows.ni.dll!System.Windows.Threading.Dispatcher.Dispatch(System.Windows.Threading.DispatcherPriority priority)
System.Windows.ni.dll!System.Windows.Threading.Dispatcher.OnInvoke(object context)
System.Windows.ni.dll!System.Windows.Hosting.CallbackCookie.Invoke(object[] args)
    System.Windows.RuntimeHost.ni.dll!System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(System.IntPtr pHandle, int nParamCount, System.Windows.Hosting.NativeMethods.ScriptParam* pParams, System.Windows.Hosting.NativeMethods.ScriptParam* pResult)

检查互联网连接时出现异常

首先,您应该避免在应用程序启动或初始化期间调用消息框。有时它会给你错误:

"显示消息框错误。最常见的原因是在应用程序启动或激活时试图调用Show。在调用Show之前等待页面导航事件。"

可以使用Debug.WriteLine("Connected.");代替MessageBox.Show("Connected.");

另一件事是,如果这是不工作检查能力,你已经给出或不访问互联网连接。

如果我使用你的代码:

    if (NetworkInterface.GetIsNetworkAvailable())
    {
        Debug.WriteLine("Connected.");
    }

应该用try-catch块包围显示的代码

,

try
{
  if (NetworkInterface.GetIsNetworkAvailable())
  {
    MessageBox.Show("Connected.");
  }
}
catch (Exception e)
{
  MessageBox.Show(e.Message);
}

这是一个非常粗糙的异常处理,你可以在这里阅读更多内容http://www.dotnetperls.com/exception