zoukankan      html  css  js  c++  java
  • C#知识点集锦(六)捕捉子线程中的异常

    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

    方式2:使用Task的 Wait

    class Program
    {
        static void Main(string[] args)
        {
            Task<int> task = new Task<int>(Test);
            task.Start();
    
            try
            {
                task.Wait();
            }
            catch (AggregateException ex)
            {
                Console.WriteLine(ex);    
            }
    
            Console.ReadLine();
        }
    
        static int Test()
        {
            throw new Exception();
        }
    }
  • 相关阅读:
    JPA与Hibernate的关系
    EJB里的问题解答
    EJB与JPA的关系
    EJB的魅惑来源
    EJB简介
    MyEclipse如何恢复删掉的文件
    EasyUI的功能树之扁平化
    EasyUI的功能树之异步树
    Spring AOP的日志记录
    简单理解IoC与DI
  • 原文地址:https://www.cnblogs.com/noigel/p/15188497.html
Copyright © 2011-2022 走看看