Pattern to avoid nested try catch blocks?

后端 未结 16 567
無奈伤痛
無奈伤痛 2020-12-12 12:53

Consider a situation where I have three (or more) ways of performing a calculation, each of which can fail with an exception. In order to attempt each calculation until we f

16条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 13:22

    You can use a Task/ContinueWith, and check for the exception. Here's a nice extension method to help make it pretty:

        static void Main() {
            var task = Task.Factory.StartNew(Calc1)
                .OrIfException(Calc2)
                .OrIfException(Calc3)
                .OrIfException(Calc4);
            Console.WriteLine(task.Result); // shows "3" (the first one that passed)
        }
    
        static double Calc1() {
            throw new InvalidOperationException();
        }
    
        static double Calc2() {
            throw new InvalidOperationException();
        }
    
        static double Calc3() {
            return 3;
        }
    
        static double Calc4() {
            return 4;
        }
    }
    
    static class A {
        public static Task OrIfException(this Task task, Func nextOption) {
            return task.ContinueWith(t => t.Exception == null ? t.Result : nextOption(), TaskContinuationOptions.ExecuteSynchronously);
        }
    }
    

提交回复
热议问题