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
    }
    }
    }
    }
  • 相关阅读:
    电影
    Python中__init__方法介绍
    学习笔记(1?)
    python参数传递
    #!/usr/bin/env python与#!/usr/bin/python
    面向对象程序设计
    Python模块学习 random 随机数生成
    正则表达式前缀r
    python 去除 list 重复元素
    python datetime处理时间
  • 原文地址:https://www.cnblogs.com/zanxiaofeng/p/2317833.html
Copyright © 2011-2022 走看看