Sunday, August 7, 2016

4. Exception handling in Async method



We can put try ..catch block in Async method to handle exception, we can put await statement inside of try..catch block or can use try ..catch in child method like...

  

       public static void Main()
        {
            Console.WriteLine("Calling Async method...");
            Task<double> result = DivideAsync(9, 0);
            Console.WriteLine("Division Result=" + result.Result);
         }

        public async static Task<double> DivideAsync(int a, int b)
        {
           Double result= await Task.Run<double>(()=>Divide(a,b));
           return result;
        }
        public static double Divide(int a, int b)
        {
            double r = 0;
            try
            {
                Thread.Sleep(5000);
                r = a / b;
            }
            catch (Exception ex)
            {
                //Log exception or show it to user
                MessageBox.Show(ex.Message);
            }
            return r;

        }

No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...