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
    }
    }
    }
    }
  • 相关阅读:
    Faster R-CNN
    06.看板实践——限制在制品
    05.看板方法——在制品
    04.看板实践——工作项
    03.看板实战——工作可视化
    02.看板实践——理解看板
    01.看板实践——学习看板(笔记)
    00.看板实践——前言(笔记)
    00.Scrum指南
    02.有效的项目管理——什么是项目管理
  • 原文地址:https://www.cnblogs.com/zanxiaofeng/p/2317833.html
Copyright © 2011-2022 走看看