
























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;
}
方法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
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。