运行线程时,我的 Try Catch 块应该在哪里? [英] Where should my Try Catch block be when running a thread?

查看:36
本文介绍了运行线程时,我的 Try Catch 块应该在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以这个线程:

Thread thread = new Thread(delegate()
            {
                //Code
            });

            thread.Start();

应该在thread.Start();周围还是里面:

Thread thread = new Thread(delegate()
            {
                try
                {
                    //Code
                }
                catch (Exception)
                {
                    //Code
                }
            });

推荐答案

放在里面还是放在外面完全不同.

it is completely different to put then inside or outside.

如果将它们放在 thread.Start() 调用周围,则可以检测到(根据此页面:http://msdn.microsoft.com/en-us/library/system.threading.thread.start(v=vs.71).aspx)

If you put them around the thread.Start() call, you can detect (according to this page: http://msdn.microsoft.com/en-us/library/system.threading.thread.start(v=vs.71).aspx)

  • ThreadStateException 线程已经启动.
  • SecurityException 调用方没有适当的 SecurityPermission.
  • OutOfMemoryException 没有足够的可用内存来启动该线程.
  • NullReferenceException 此方法是在一个线程引用上调用的,该线程引用是一个空引用(在 Visual Basic 中为 Nothing).

如果你把它放在里面,你会在你的线程中运行的代码中检测到异常.所以任何你想要的例外.

If you put it inside, you will detect exception inside the code you will run in your thread. So any kind of exception you want.

这篇关于运行线程时,我的 Try Catch 块应该在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆