C# 并行编程避坑指南之-Try Catch系列

自从.NET Framework 4.5+(含4.5)提供了Task开启线程后,基本上Thread的使用频率就大幅度降低了,但是一些老项目,或者老程序还是习惯用Thread去做,如果一定要使用Thred,那我们就必须在代码中使用try、catch块去处理异常的。

因为Thred的代码抛出异常将会是的应用程序被强制关闭,如果要避免这种情况的发生,就需要正确编写try/catch代码块。.

错误的写法如下:

 static void Main()        {            try            {                var thread = new Thread(new ThreadStart(BadThread));                thread.Start();            }            catch (Exception ex)            {                Console.WriteLine("you can not catch exception here!");            }
            Console.ReadKey();        }
        private static void BadThread()        {            Console.WriteLine("A faulty thread started...");            Thread.Sleep(100);            throw new Exception("Faulted!!!");        }

运行后直接崩溃了,如下图所示:

C# 并行编程避坑指南之-Try Catch系列

try catch应该放置到代码块内部去捕获异常。

正确的做法应该这样:

static void Main()        {            var thread = new Thread(CorrectThread);            thread.Start();            thread.Join();
            Console.WriteLine("A faulty thread started...");            Console.ReadKey();        }
        private static void CorrectThread()        {            try            {                Console.WriteLine("A faulty thread started...");                Thread.Sleep(100);                throw new Exception("Faulted!!!");            }            catch (Exception ex)            {                Console.WriteLine($"Exception handled : {ex}");            }        }

总结:就个人而言,目前是能用task尽量不用thread,那thread没有用武之地吗,也不是。thread适合长时间运行的线程,task呢,小巧玲珑,它是通过线程池实现的,不用的时候可以自动回收,使用起来很方便。thread默认为前台线程,主程序必须等线程跑完才会关闭,但是可以通过设置IsBackground,设置为后台线程,而threadpool则默认是后台线程,Task由于是用线程池实现的本地队列,性能优越,同时Task提供了丰富的API来管理线程、控制。