栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

C#多线程异常处理

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#多线程异常处理

C#的子线程的异常处理,直接上代码吧。
首先是Thread,下面这种情况程序会直接抛异常

        static void Main(string[] args)
        {
            try
            {
                Thread th = new Thread(Th);
                th.Start();
            }
            catch (Exception ex)
            {
                //此处永远不会被执行
                Console.WriteLine("get ex in child thread");
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }

        static void Th()
        {
            string s = null;
            int a = s.Length;
        }

下面在子线程中添加异常捕捉:

        static void Main(string[] args)
        {
            try
            {
                Thread th = new Thread(Th);
                th.Start();
            }
            catch (Exception ex)
            {
                //此处永远不会被执行
                Console.WriteLine("get ex in child thread");
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }

        static void Th()
        {
            try
            {
                string s = null;
                int a = s.Length;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

执行结果:

综上所述,使用Thread时,子线程的异常需要在子线程的内部自行处理,主线程无法捕获子线程的异常。

下面来看看使用Task的情况

        static void Main(string[] args)
        {
            try
            {
                Task t = Task.Run(() =>
                  {
                      string s = null;
                      int a = s.Length;
                  });

                t.Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine("get ex in child thread");
                Console.WriteLine($"the type of Exception is: {ex.GetType().Name}");
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }

运行结果:

下面用异步函数的方式:

        static async Task Main(string[] args)
        {
            try
            {
                await Task.Run( async () =>
                {
                    string s = null;
                    int a = s.Length;
                    await Task.Delay(100);
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("get ex in child thread");
                Console.WriteLine($"the type of Exception is: {ex.GetType().Name}");
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }

看看运行结果:

由此可见使用Task和异步函数,可以对异常更加方便的处理,若使用Thread类创建的线程,则需要在子线程代码中处理异常。
对异常进行合适的处理对于程序的健壮性有很大的好处,更重要的是当出现问题的时候可以快速定位到问题。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908939.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号