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
    }
    }
    }
    }
  • 相关阅读:
    【codeforces 723F】stSpanning Tree
    struts2.0中struts.xml配置文件详解
    存储过程中调用JAVA程序段
    本不该逃避
    利用js实现对页面的自动刷新
    [转]从硬盘安装 RedHat Enterprise Linux Server 5 iso
    正则表达式使用
    利用XmlBean轻松读写xml(转)
    Struts2+Spring2+Hibernate3 web应用示例(七)
    在DWR中实现直接获取一个JAVA类的返回值的两种方法
  • 原文地址:https://www.cnblogs.com/zanxiaofeng/p/2317833.html
Copyright © 2011-2022 走看看