.Net 2 Tip :捕获CSE和Thread.Timer与Thread.Sleep比较

  • 在.Net如何捕获 AccessViolationException
    在.net4.0 中,系统某些SEH异常默认是不被捕获的,该类异常称作Corrupted State Exceptions (CSE)
    比如:调用非托管代码时,常常会出现此类错误,如"内存不可读/写".
    MS的MSDN有篇文章详细介绍了CSE异常:
    http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035

    MS不推荐,捕获此类异常,因为此类异常不解决,应用可能会导致更严重的错误.建议重启该应用程序.出现此类异常的原因,往往需要解决.而不是简单的的捕获.所以.NET4.0中不让捕了(早干啥去了,到.NET才这样处理).但有些时候,我们的确要捕获此类异常,或者说调用的是第三方的库.我们根本无法彻底解决这种问题. .NET4.0 提供了如下的方法捕获:

    // This program runs as part of an automated test system so you need
    // to prevent the normal Unhandled Exception behavior (Watson dialog).
    // Instead, print out any exceptions and exit with an error code.
    [HandleProcessCorruptedStateExceptions]
    public static int Main()
    {
       try
         {
           // Catch any exceptions leaking out of the program CallMainProgramLoop();
         }
       catch (Exception e)
           // We could be catching anything here
         {
             // The exception we caught could have been a program error
            // or something much more serious. Regardless, we know that
            // something is not right. We'll just output the exception
           // and exit with an error. We won't try to do any work when
           // the program or process is in an unknown state!

            System.Console.WriteLine(e.Message);
            return 1;
         }

      return 0;

    }

  • 使用Timer还是Thread.Sleep
    当你需要间隔一段时间执行一个方法时.你是否在方法1,和方法2中悱徊?
    方法1.
    Thread thread = new Thread(() => {
        Thread.Sleep(millisecond);
        action();
    });
    thread.IsBackground = true;
    thread.Start();


    方法2:
    Timer timer = new Timer(o => action(), null, millisecond, -1);

    如果你仅仅是需要间断一段时间执行一个方法.推荐使用timer.
    下面MS MVP 严重批评了使用Thread.Sleep.
    http://msmvps.com/blogs/peterritchie/archive/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program.aspx

    此人认为如果你在代码中使用thread.sleep.说明该代码设计是糟糕的.Thread.Sleep 的应用场景只有在测试和Debug时需要模拟一个操作的执行时间.
    1). 使用Thread的开销很大,大概需要200,000 cpu周期去创建一个线程, 100,000 个周期去销毁.timer的方法是进程内部的线程池的线程.这也是使用 ThreadPool.QueueUserWorkItem优于new 一个thread的地方.
    2).thread.sleep 无法解决问题,只会让问题更难以重现.
    2).其次创建一个线程后,比如关闭窗体,这个线程在退出时需要显示强行退出.也很不方便.相反使用timer

posted on 2011-09-27 17:23  Haozes  阅读(1554)  评论(0编辑  收藏  举报