简体   繁体   English

WinForms - 当应用程序启动时没有可用的互联网连接时,mscorlib.dll 中的 System.Reflection.TargetInvocationException

[英]WinForms - System.Reflection.TargetInvocationException in mscorlib.dll when no internet connection is available on application start

I've made a simple desktop application (Winform, in Visual Studio 2015, .NET version 4.5.2) which listens for incoming pusher.com notifications, and does various things depending on what the notification contains.我制作了一个简单的桌面应用程序(Winform,在 Visual Studio 2015 中,.NET 版本 4.5.2),它侦听传入的 pusher.com 通知,并根据通知包含的内容执行各种操作。 However, there are some issues regarding the internet connectivity - if there is no connection on startup, the application crashes, because of an unhandled exception:但是,互联网连接存在一些问题 - 如果启动时没有连接,应用程序会因未处理的异常而崩溃:

An unhandled exception of type System.Reflection.TargetInvocationException occurred in in mscorlib.dll

The InnerException is No such host is known , and it's understandable, since there's no internet connection. InnerExceptionNo such host is known ,这是可以理解的,因为没有互联网连接。

The StartPushing() bit of the code will continue trying to reconnect if the connection is interrupted while the app is running, and unstable connection is not (the biggest) problem.如果在应用程序运行时连接中断,代码的StartPushing()位将继续尝试重新连接,并且不稳定的连接不是(最大的)问题。 It's not having the connection before the application is run.在应用程序运行之前它没有连接。

I've also removed StartPushing() from public Form1()1 and placed it within Form1_Shown(...) (thinking that maybe it was called before everything had been setup), but that did not solve the problem - the application kept crashing on startup.我还从public Form1()1删除了StartPushing()并将其放置在Form1_Shown(...) (认为​​它可能在所有设置之前就被调用了),但这并没有解决问题 - 应用程序不断崩溃在启动时。

This is my code.这是我的代码。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Forms;
using Newtonsoft.Json;
using PusherClient;


namespace PusherWebApps
{
    public partial class Form1 : Form
    {
        private static Pusher _pusher;
        public string channel, key;
        public string event1, event2;
        public string iniName = "PusherWebApps.ini";
        public string type;
        WebClient client = new WebClient();

        public Form1()
        {
            InitializeComponent();
            // https://stackoverflow.com/a/39308022
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            StartPushing();
        }

        void _pusher_ConnectionStateChanged(object sender, PusherClient.ConnectionState state)
        {
            fileLogging("Connection state: " + state.ToString());
        }

        void _pusher_Error(object sender, PusherException error)
        {
            fileLogging("Pusher Channels Error: " + error.ToString());
        }

        // Start
        public async void StartPushing()
        {
            iniParams();
            _pusher = new Pusher(key);
            _pusher.ConnectionStateChanged += _pusher_ConnectionStateChanged;
            _pusher.Error += _pusher_Error;
            PusherClient.ConnectionState connectionState = await _pusher.ConnectAsync();

            Channel _myChannel = await _pusher.SubscribeAsync(channel);

            _myChannel.Bind("myevent", (dynamic incoming) =>
            {
                fileLogging(incoming.ToString());

                dynamic tmp = JsonConvert.DeserializeObject(incoming.ToString());
                dynamic data = JsonConvert.DeserializeObject(tmp.data.ToString());
                dynamic message = JsonConvert.DeserializeObject(data.message.ToString());
                dynamic header = JsonConvert.DeserializeObject(message.header.ToString());

                type = header.type.ToString();

                if (type.ToLower() == event1)
                {
                    // do stuff
                }

                if (type.ToLower() == event2)
                {
                    // do stuff 2
                }
            });
        }

        void _myChannel_Subscribed(object sender)
        {
            fileLogging("Subscribed!");
        }

        public void iniParams()
        {
            bool checkIni = File.Exists(Application.StartupPath + "\\" + iniName);

            if(!checkIni)
            {
                fileLogging("INI missing!");
                MessageBox.Show("INI missing!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(0);
            }

            var MyIniFile = new IniFile(Application.StartupPath + "\\" + iniName);

            channel = MyIniFile.Read("channel", "Main").ToString();
            key = MyIniFile.Read("key", "Main").ToString();
            event1 = MyIniFile.Read("event1", "Main").ToString();
            event2 = MyIniFile.Read("event2", "Main").ToString();
        }

/************ BEGIN logging **********/
        public void fileLogging(string text)
        {
            // do logging stuff
        }
/********** END logging *********/
    }
}

Finally, my question.最后,我的问题。

How can I handle this error?我该如何处理这个错误?

I know that I could probably inform the user that there's no internet connection at startup, and then exit the application, but I'd like to keep it running, and let it keep trying to connect in the background.我知道我可能会在启动时通知用户没有互联网连接,然后退出应用程序,但我想保持它运行,并让它继续尝试在后台连接。 I would also like to avoid having to use a separate thread and a timer to check for internet connectivity in the background.我还想避免在后台使用单独的线程和计时器来检查互联网连接。

EDIT 1编辑 1

This is the part to which the debugger points - instead of pointing somewhere inside Form1.cs , it highlights this part of Program.cs这是调试器指向的部分 - 而不是指向Form1.cs某处,而是突出显示Program.cs这一部分

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1()); // <== this is the one which the debugger highlights as the error
    }
}

Just add a try/catch to your code.只需在您的代码中添加一个 try/catch。 If the app has a GUI or something like that and you want the final user to be able to see it even if it has no internet, you can add the try/catch just to the WebClient part instead of the whole code.如果应用程序具有 GUI 或类似的东西,并且您希望最终用户即使在没有互联网的情况下也能看到它,您可以将 try/catch 仅添加到 WebClient 部分而不是整个代码。

暂无
暂无

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

相关问题 mscorlib.dll中发生类型&#39;System.Reflection.TargetInvocationException&#39;的异常,但未在用户代码中处理 - An exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll but was not handled in user code RelayCommand和异步方法导致:“ mscorlib.dll中发生了&#39;System.Reflection.TargetInvocationException&#39;” - RelayCommand and async method resulting: “'System.Reflection.TargetInvocationException' occurred in mscorlib.dll” mscorlib:System.reflection.TargetInvocationException - mscorlib:System.reflection.TargetInvocationException mscorlib.ni.dll中发生类型&#39;System.Reflection.TargetInvocationException&#39;的异常,但未在用户代码中处理:Xamarin形式 - An exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.ni.dll but was not handled in user code: in Xamarin Form 当我运行MVC 4应用程序时出现System.Reflection.TargetInvocationException - System.Reflection.TargetInvocationException when i run MVC 4 application System.Reflection.TargetInvocationException - System.Reflection.TargetInvocationException EntityFramework.SqlServer.dll 中发生“System.Reflection.TargetInvocationException” - 'System.Reflection.TargetInvocationException' occurred in EntityFramework.SqlServer.dll C# dll System.Reflection.TargetInvocationException 错误 - C# dll System.Reflection.TargetInvocationException error System.Reflection.TargetInvocationException&#39;出现在PresentationFramework.dll中 - System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll 构造函数中的 System.Reflection.TargetInvocationException - System.Reflection.TargetInvocationException in constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM