I would like to validate our code and check if every Thread that we execute runs in try catch block.
A valid sample:
Thread loadDataThread = new Thread(new ThreadStar开发者_如何转开发t(LoadData));
public void LoadData()
{
try {/*do something*/}
catch(Exception ex) { /*Handle exception*/ }
}
Not valid sample:
Thread loadDataThread = new Thread(new ThreadStart(LoadData));
public void LoadData()
{
/* do something */
}
Is this something that could be verified with FxCop or some other tool. The similar rule could be applied for some other things eg. Timer Ticks etc...
See http://social.msdn.microsoft.com/Forums/en-US/vstscode/thread/a257a910-126e-4c8d-aab3-3199347346ec for an example of how to detect a wrapping try/catch block in an FxCop rule. What's actually quite a bit trickier to do is detect which methods are susceptible to being run from a background thread since they're not all spawned using obvious launchers like Thread.Start or ThreadPool.QueueUserWorkItem.
That said, you might want to reconsider switching your approach from adding wrapping try/catches to using custom thread launchers that add the try/catch for you. (You could then create an FxCop rule to verify that the custom launchers/helpers are being used instead of the base framework analogs.) This would have the advantage of allowing you to systematically apply other changes to all thread (e.g.: setting cultures, tracking launching stack trace for use in later exception logging, etc.) without needing to change all the methods run from spawned threads.
I do not know if you can add a custom rule for this in FXCop, but you could use Mono.Cecil
to do this, but it is not that simple.
This is a very good resource for rolling your own FxCop rule. You may find many other by googling for the same.
I believe that you can start looking at callers for Thread constructor. Then in calling statement, you can get address of thread procedure by looking at the delegate parameter. Once method ref is obtained, you need inspect statements within method body for the structure you are hoping for.
this does not answer your question directly but is probably pertinent.
Are you interested in doing the above because you do not want your application to exit/crash when a thread throws an uncaught Exception? If yes, then you can add the following to your app.config file in the configuration section:
<runtime>
<legacyUnhandledExceptionPolicy enabled="1"/>
</runtime>
disclaimer Doing the above is not recommended but may be used in a situation of last resort.
Warning: If you decide to use the above your application will not report any errors and go on executing as best it can. As a result you should have a handler that will at least log any uncaught exceptions via
void AppStartup()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//log error
}
精彩评论