首页 > 编程语言 > 详细

C#知识点集锦(六)捕捉子线程中的异常

时间:2021-08-26 11:41:05      阅读:12      评论:0      收藏:0      [点我收藏+]

1使用Task

        public Form1()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            Task<int> task = new Task<int>(test);
            task.ContinueWith(Handler, TaskContinuationOptions.OnlyOnFaulted);
            task.Start();
        }

        private void Handler(Task<int> obj)
        {
            string id=("In handler thread ,id is " + Thread.CurrentThread.ManagedThreadId);
            var exception = obj.Exception;
            MessageBox.Show($"With thread id {id}, exception: {exception}");
        }

        private int test()
        {
            Console.WriteLine("In test thread ,id is " + Thread.CurrentThread.ManagedThreadId);
            throw new NotImplementedException();
        }

输出:控制台输出

In test thread ,id is 3

消息框输出:in handler Thread id is4

C#知识点集锦(六)捕捉子线程中的异常

原文:https://www.cnblogs.com/noigel/p/15188497.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!