C# 检查internet连接期间未处理的异常
我想在App.xaml.cs文件中检查internet连接,但当我在构造函数中执行此操作时,它会抛出未处理的异常,为什么?有可能这样做吗?例如,当我签入MainPage.xaml.cs时,它就工作了 我的代码:C# 检查internet连接期间未处理的异常,c#,xaml,windows-phone-8,C#,Xaml,Windows Phone 8,我想在App.xaml.cs文件中检查internet连接,但当我在构造函数中执行此操作时,它会抛出未处理的异常,为什么?有可能这样做吗?例如,当我签入MainPage.xaml.cs时,它就工作了 我的代码: if (NetworkInterface.GetIsNetworkAvailable()) { MessageBox.Show("Connected."); } 调用堆栈: App.Application_UnhandledException(object sender, Sy
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)
您应该将显示的代码包围在try-catch块中 例如:
这是一个相当粗糙的异常处理,您可以在此处阅读更多内容首先,您应该避免在应用程序启动或初始化期间调用消息框。有时,它会给您带来以下错误: 显示MessageBox时出错。最常见的原因是在应用程序启动或激活时试图调用Show。在调用Show之前等待页面导航事件 您可以使用Debug.WriteLineConnected。;而是MessageBox.ShowConnected 另一件事是,如果这不起作用,请检查您是否提供了访问internet连接的功能 如果我将您的代码用作:
if (NetworkInterface.GetIsNetworkAvailable())
{
Debug.WriteLine("Connected.");
}
工作正常。显示您收到的错误!!我仍然没有收到任何消息框,即使有例外。是否可以在App.xaml.cs构造函数中检查连接?欢迎使用。因此,标记为已回答,以供其他人将来参考。
if (NetworkInterface.GetIsNetworkAvailable())
{
Debug.WriteLine("Connected.");
}