查看文章
 
AppDomain的两个小技巧(程序运行完毕和未处理异常的处理)
2008-11-28 23:56

有时候,我们会需要在程序结束时进行一些处理,比如记录log日志,清除一些临时文件等工作。这时候我们可以利用AppDomainProcessExit事件:

class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += (sender, arg) =>
                File.WriteAllText(@"c:\log.txt", ((AppDomain)sender).FriendlyName);
    }
}

当程序运行完毕时,将会在C盘创建一个log.txt的文件,并写入我们指定的信息。一般参数中的sender为事件所属类的实例。

值得注意的是,当程序发生异常中断时,上述退出事件是不会执行的,这时候我们可以借助AppDomainUnhandledException事件:

class Program
{
    static void Main(string[] args)
 {
        AppDomain.CurrentDomain.UnhandledException += (sender, arg) =>
            File.WriteAllText(@"c:\log.txt", ((Exception)arg.ExceptionObject).StackTrace);

        throw new Exception("err!!");
    }
}

配合着这两个事件的使用,我们可以对程序建立起完善的监督机制,再也不用担心异常发生后找不着,也不用担心日志信息记录因为出错而缺失。


类别:Dotnet||添加到搜藏 |分享到i贴吧|浏览(565)|评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
     

   
帮助中心 | 空间客服 | 投诉中心 | 空间协议
©2012 Baidu