zoukankan      html  css  js  c++  java
  • .NET下未处理异常导致进程意外终止

    如果.NET下的一个多线程程序不能正确的处理异常将很有可能会发生由于未处理异常导致进程意外终止的情况,尤其是在使用System.Threading.Timer的时候,由于TimerCallBack是在一个单独的线程中执行的,因此在TimerCallBack方法中发生异常而没有Catch的话将会导致未处理异常是进程意外终止。

    如下的代码所示:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;

    namespace TestUnhandleException
    {
    class Program
    {
    static void Main(string[] args)
    {
    Timer timer = new Timer(TimerCallback, null, 10000, 10000);
    Console.ReadLine();
    }

    private static void TimerCallback(object obj)
    {
    throw new Exception("Throw a unHandledException for test");
    }
    }
    }

    上面的程序启动后10秒钟便会意外终止,如果查看Windows EventLog的话将会看到下面的两条Log:

    正确的做法如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;

    namespace TestUnhandleException
    {
    class Program
    {
    static void Main(string[] args)
    {
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    Timer timer = new Timer(TimerCallback, null, 10000, 10000);
    Console.ReadLine();
    }

    private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
    //Todo:Log
    }

    private static void TimerCallback(object obj)
    {
    try
    {
    throw new Exception("Throw a unHandledException for test");
    }
    catch(Exception)
    {
    //Todo:Log
    }
    }
    }
    }
  • 相关阅读:
    robot framework 实例:126邮箱登录
    python帮助文档查看
    robot framework 测试库安装
    robot framework 变量与常量
    robot framework连接mysql数据库
    、搭建Android开发环境
    基于Eclipse的Android开发环境搭建
    MySQLzip压缩文件格式安装教程
    tomcat版本号的修改
    java时间格式
  • 原文地址:https://www.cnblogs.com/zanxiaofeng/p/2317833.html
Copyright © 2011-2022 走看看