Catch exception from other thread

Posted on 2012-07-02 15:35  leon_ALiang  阅读(315)  评论(0编辑  收藏  举报
 class Class2 {
        static void Main(string[] args) {
            Exception exception = null;
            Thread thread = new Thread(() => SafeExecute(() => Test(0, 0), out exception));
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
            thread.Start();

            thread.Join();

            Console.WriteLine(exception);

            Console.ReadLine();
        }

        private static void SafeExecute(Action test, out Exception exception) {
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
            exception = null;

            try {
                test();
            }
            catch (Exception ex) {
                exception = ex;
            }
        }

        static void Test(int a, int b) {
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
            throw new Exception();
        }

  

Copyright © 2024 leon_ALiang
Powered by .NET 9.0 on Kubernetes