C# App.xaml.cs的一些操作

一、保证只有一个进程

1.1 关闭旧的,打开新的

   protected override void OnStartup(StartupEventArgs e) {
            base.OnStartup(e);
            var process =Process.GetProcessesByName("Dog");
            if (process.Count() > 1) {
                var list = process.ToList();
                list.Sort((p1,p2)=>p1.StartTime.CompareTo(p2.StartTime));
                list[0].Kill();
            }
        }

1.2 程序打开后不再打开新程序

 protected override void OnStartup(StartupEventArgs e) {
            base.OnStartup(e);
            var process =Process.GetProcessesByName("Dog");
            if (process.Count() > 1) {
                MessageBox.Show("已经打开一个程序");
                Process.GetCurrentProcess().Kill();
            }
        }

二、异常捕捉

   public App()
        {
        //注册全局事件
           AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            DispatcherUnhandledException += App_DispatcherUnhandledException;

            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

        }

    private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args)
    {
        const string msg = "主线程异常";
        try
        {
            if (args.ExceptionObject is Exception && Dispatcher != null)
            {
                Dispatcher.Invoke(() =>
                {
                    Exception ex = (Exception)args.ExceptionObject;
                    HandleException(msg, ex);
                });
            }
        }
        catch (Exception ex)
        {
            HandleException(msg, ex);
        }
    }

    private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs args)
    {
        const string msg = "子线程异常";
        try
        {
            HandleException(msg, args.Exception);
            args.Handled = true;
        }
        catch (Exception ex)
        {
            HandleException(msg, ex);
        }
    }

    private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs args)
    {
        const string msg = "异步异常";
        try
        {
            HandleException(msg, args.Exception);
            args.SetObserved();
        }
        catch (Exception ex)
        {
            HandleException(msg, ex);
        }
    }

    private void HandleException(string msg, Exception ex)
    {

            MessageBox.Show(ex.Message,msg);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值