原文地址:https://blog.csdn.net/fxfeixue/article/details/4466899

这是因为.NET Framework 1.0 和 1.1 这两个版本对许多未处理异常(例如,线程池线程中的未处理异常)提供支撑,而 Framework 2.0 版中,公共语言运行库允许线程中的多数未处理异常自然继续。在多数情况下,这意味着未处理异常会导致应用程序终止。

一、C/S 解决方案(以下任何一种方法)
1. 在应用程序配置文件中,添加如下内容:
<configuration>
  <runtime>
    <legacyUnhandledExceptionPolicy enabled="true" />
  </runtime> 
</configuration>

2. 在应用程序配置文件中,添加如下内容:
<configuration>
  <startup>
    <supportedRuntime version="v1.1.4322"/>
  </startup>
</configuration>

3. 使用Application.ThreadException事件在异常导致程序退出前截获异常。示例如下:
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Main(string[] args)
{
    Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

Application.Run(new ErrorHandlerForm());
}

// 在主线程中产生异常
private void button1_Click(object sender, System.EventArgs e)
{
    throw new ArgumentException("The parameter was invalid");
}

// 创建产生异常的线程
private void button2_Click(object sender, System.EventArgs e)
{
    ThreadStart newThreadStart = new ThreadStart(newThread_Execute);
    newThread = new Thread(newThreadStart);
    newThread.Start();
}

// 产生异常的方法
void newThread_Execute()
{
    throw new Exception("The method or operation is not implemented.");
}

private static void Form1_UIThreadException(object sender, ThreadExceptionEventArgs t)
{
    DialogResult result = DialogResult.Cancel;
    try
    {
        result = ShowThreadExceptionDialog("Windows Forms Error", t.Exception);
    }
    catch
    {
        try
        {
            MessageBox.Show("Fatal Windows Forms Error",
                "Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
        }
        finally
        {
            Application.Exit();
        }
    }

if (result == DialogResult.Abort)
        Application.Exit();
}

// 由于 UnhandledException 无法阻止应用程序终止,因而此示例只是在终止前将错误记录在应用程序事件日志中。
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    try
    {
        Exception ex = (Exception)e.ExceptionObject;
        string errorMsg = "An application error occurred. Please contact the adminstrator " +
            "with the following information:/n/n";

if (!EventLog.SourceExists("ThreadException"))
        {
            EventLog.CreateEventSource("ThreadException", "Application");
        }

EventLog myLog = new EventLog();
        myLog.Source = "ThreadException";
        myLog.WriteEntry(errorMsg + ex.Message + "/n/nStack Trace:/n" + ex.StackTrace);
    }
    catch (Exception exc)
    {
        try
        {
            MessageBox.Show("Fatal Non-UI Error",
                "Fatal Non-UI Error. Could not write the error to the event log. Reason: "
                + exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
        finally
        {
            Application.Exit();
        }
    }
}

private static DialogResult ShowThreadExceptionDialog(string title, Exception e)
{
    string errorMsg = "An application error occurred. Please contact the adminstrator " +
        "with the following information:/n/n";
    errorMsg = errorMsg + e.Message + "/n/nStack Trace:/n" + e.StackTrace;
    return MessageBox.Show(errorMsg, title, MessageBoxButtons.AbortRetryIgnore,
        MessageBoxIcon.Stop);
}

二、B/S 解决方案(以下任何一种方法)
1. 在IE目录(C:/Program Files/Internet Explorer)下建立iexplore.exe.config文件,内容如下:
<?xml version="1.0"?> 
<configuration>
  <runtime>
    <legacyUnhandledExceptionPolicy enabled="true" />
  </runtime> 
</configuration>

2. 不建议使用此方法,这将导致使用 framework 1.1 以后版本的程序在IE中报错。
建立同上的配置文件,但内容如下:
<?xml version="1.0"?> 
<configuration>
  <startup>
    <supportedRuntime version="v1.1.4322"/>
  </startup>
</configuration>

3. 这个比较繁琐,分为三步:
⑴. 将下面的代码保存成文件,文件名为UnhandledExceptionModule.cs,路径是C:/Program Files/Microsoft Visual Studio 8/VC/
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Web;
 
namespace WebMonitor {
    public class UnhandledExceptionModule: IHttpModule {

static int _unhandledExceptionCount = 0;

static string _sourceName = null;
        static object _initLock = new object();
        static bool _initialized = false;

public void Init(HttpApplication app) {

// Do this one time for each AppDomain.
            if (!_initialized) {
                lock (_initLock) {
                    if (!_initialized) { 
                        string webenginePath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "webengine.dll");

if (!File.Exists(webenginePath)) {
                            throw new Exception(String.Format(CultureInfo.InvariantCulture,
                                                             
"Failed to locate webengine.dll at '{0}'.  This module requires .NET
Framework 2.0.", 
                                                              webenginePath));
                        }

FileVersionInfo ver = FileVersionInfo.GetVersionInfo(webenginePath);
                        _sourceName = string.Format(CultureInfo.InvariantCulture, "ASP.NET {0}.{1}.{2}.0",
                                                    ver.FileMajorPart, ver.FileMinorPart, ver.FileBuildPart);

if (!EventLog.SourceExists(_sourceName)) {
                            throw new Exception(String.Format(CultureInfo.InvariantCulture,
                                                             
"There is no EventLog source named '{0}'. This module requires .NET
Framework 2.0.", 
                                                              _sourceName));
                        }
 
                        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
 
                        _initialized = true;
                    }
                }
            }
        }

public void Dispose() {
        }

void OnUnhandledException(object o, UnhandledExceptionEventArgs e) {
            // Let this occur one time for each AppDomain.
            if (Interlocked.Exchange(ref _unhandledExceptionCount, 1) != 0)
                return;

StringBuilder message = new
StringBuilder("/r/n/r/nUnhandledException logged by
UnhandledExceptionModule.dll:/r/n/r/nappId=");

string appId = (string) AppDomain.CurrentDomain.GetData(".appId");
            if (appId != null) {
                message.Append(appId);
            }
            
            Exception currentException = null;
           
for (currentException = (Exception)e.ExceptionObject; currentException
!= null; currentException = currentException.InnerException) {
                message.AppendFormat("/r/n/r/ntype={0}/r/n/r/nmessage={1}/r/n/r/nstack=/r/n{2}/r/n/r/n",
                                     currentException.GetType().FullName, 
                                     currentException.Message,
                                     currentException.StackTrace);
            }

EventLog Log = new EventLog();
            Log.Source = _sourceName;
            Log.WriteEntry(message.ToString(), EventLogEntryType.Error);
        }
    }
}

⑵. 打开Visual Studio 2005的命令提示行窗口 
输入Type sn.exe -k key.snk后回车
输入Type csc /t:library /r:system.web.dll,system.dll /keyfile:key.snk UnhandledExceptionModule.cs后回车
输入gacutil.exe /if UnhandledExceptionModule.dll后回车
输入ngen install UnhandledExceptionModule.dll后回车 
输入gacutil /l UnhandledExceptionModule后回车并将显示的”强名称”信息复制下来

⑶. 打开ASP.net应用程序的Web.config文件,将下面的XML加到里面。注意:不包括”[]”,①可能是添加到<httpModules></httpModules>之间。
<add name="UnhandledExceptionModule" type="WebMonitor.UnhandledExceptionModule, [这里换为上面复制的强名称信息]" />

三、微软并不建议的解决方案
    打开位于 %WINDIR%/Microsoft.NET/Framework/v2.0.50727 目录下的 Aspnet.config 文件,将属性 legacyUnhandledExceptionPolicy 的 enabled 设置为 true

四、跳出三界外——ActiveX
    ActiveX 的特点决定了不可能去更改每个客户端的设置,采用 B/S 解决方案里的第 3 种方法也不行,至于行不通的原因,我想可能是因为 ActiveX 的子控件产生的异常直接

被 CLR 截获了,并没有传到最外层的 ActiveX 控件,这只是个人猜测,如果有清楚的朋友,还望指正。

最终,我也没找到在 ActiveX 情况的解决方法,但这却是我最需要的,无奈之下,重新检查代码,发现了其中的问题:在子线程中创建了控件,又将它添加到了主线程的 UI 上。
    以前遇到这种情况,系统就会报错了,这次居然可以蒙混过关,最搞不懂的是在 framework 2.0 的 C/S 结构下也没有报错,偏偏在 IE(ActiveX) 里挂了。唉,都是宿主惹的祸。

(转)CLR20R3 程序终止的几种解决方案的更多相关文章

  1. C# CLR20R3 程序终止的几种解决方案 【转】

    [转]CLR20R3 程序终止的几种解决方案   这是因为.NET Framework 1.0 和 1.1 这两个版本对许多未处理异常(例如,线程池线程中的未处理异常)提供支撑,而 Framework ...

  2. C# CLR20R3 程序终止的几种解决方案

    这是因为.NET Framework 1.0 和 1.1 这两个版本对许多未处理异常(例如,线程池线程中的未处理异常)提供支撑,而 Framework 2.0 版中,公共语言运行库允许线程中的多数未处 ...

  3. C# 截获某个域中未捕获的异常 CLR20R3 程序终止的几种解决方案

    AppDomain.UnhandledException可以获的异常,却截不下来,求解 AppDomain.CurrentDomain.UnhandledException += CurrentDom ...

  4. iOS多线程全套:线程生命周期,多线程的四种解决方案,线程安全问题,GCD的使用,NSOperation的使用

    目的 本文主要是分享iOS多线程的相关内容,为了更系统的讲解,将分为以下7个方面来展开描述. 多线程的基本概念 线程的状态与生命周期 多线程的四种解决方案:pthread,NSThread,GCD,N ...

  5. C语言中的程序终止函数

    在C语言的标准库<stdlib.h>中提供了一些与正常或者不正常的程序终止有关的函数,下面分别对其进行简单介绍. 参考文献: [1] C和指针,P298,342 [2] C程序设计语言现代 ...

  6. [转]ArcGIS移动客户端离线地图的几种解决方案

    原文地址:http://blog.chinaunix.net/uid-10914615-id-3023158.html 移动GIS中,通常将数据分为两大类:basemap layer和operatio ...

  7. WPF应用程序支持多国语言解决方案

    原文:WPF应用程序支持多国语言解决方案 促使程序赢得更多客户的最好.最经济的方法是使之支持多国语言,而不是将潜在的客户群限制为全球近70亿人口中的一小部分.本文介绍四种实现WPF应用程序支持多国语言 ...

  8. linux 出错 “INFO: task xxxxxx: 634 blocked for more than 120 seconds.”的3种解决方案(转)

    linux 出错 “INFO: task xxxxxx: 634 blocked for more than 120 seconds.”的3种解决方案 1 问题描述 服务器内存满了,ssh登录失败 , ...

  9. C#实现多级子目录Zip压缩解压实例 NET4.6下的UTC时间转换 [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程 asp.net core异步进行新增操作并且需要判断某些字段是否重复的三种解决方案 .NET Core开发日志

    C#实现多级子目录Zip压缩解压实例 参考 https://blog.csdn.net/lki_suidongdong/article/details/20942977 重点: 实现多级子目录的压缩, ...

随机推荐

  1. 编写一个函数 reverse_string(char * string)实现:将参数字符串中的字符反向排列 。(递归实现)

    要求:不能使用C函数库中的字符串操作函数. 思路:在递归函数的调用时,先应该定义一个指针型char字符串.函数内部应先调用自己,在打印,这样才能保证字符串是从最后一个开始输出. #include< ...

  2. 用Promise对象实现的 Ajax 操作

  3. openstack--2--控制节点安装mysql和rabbitmq

    生产中可以把mysql数据库单独安装到一台机器上,这里因为实验机器有限,就把mysql安装到了控制节点 其实openstack每个组件都可以安装到单独的机器上. RabbitMQ介绍 RabbitMQ ...

  4. HBase源码分析之WAL

    WAL(Write-Ahead Logging)是数据库系统中保障原子性和持久性的技术,通过使用WAL可以将数据的随机写入变为顺序写入,可以提高数据写入的性能.在hbase中写入数据时,会将数据写入内 ...

  5. jdk动态代理在idea的debug模式下不断刷新tostring方法

    在jdk的动态代理下,在使用idea进入动态代理的debug模式下,单步调试会刷新idea的tostring方法,让他自己重走了一遍代理 这个问题暂时无解

  6. jsp中如何清除缓存(转)

    <% response.setHeader("Cache-Control","no-cache"); //HTTP 1.1 response.setHea ...

  7. centos服务器上部署javaweb项目(转)

    本文总体参照http://blog.csdn.net/u011019141(然后更据自己情况进行更改) 一.安装JDK 1.首先要查看服务器的系统版本,是32位还是64位 #getconf LONG_ ...

  8. [MySQL FAQ]系列 — processlist中哪些状态要引起关注 解决mysql cpu过高问题

    show processlist; 一般而言,我们在processlist结果中如果经常能看到某些SQL的话,至少可以说明这些SQL的频率很高,通常需要对这些SQL进行进一步优化. 今天我们要说的是, ...

  9. Arduino在64位WIN7下无法安装驱动的解决办法

    1.获取权限 打开C:\Windows\System32\DriverStore\FileRepository,对着FileRepository文件夹,右键 >>属性 >>安全 ...

  10. R基于Bayes理论实现中文人员特性的性别判定

    参见 基于中文人员特征的性别判定方法  理论,告诉一个名字,来猜猜是男是女,多多少少有点算命的味道.此命题是一种有监督的学习方法,从标注好的训练数据学习到一个预测模型,然后对未标注的数据进行预测. 1 ...