Wednesday, 2 September 2015

How to use ContinueWith method in Task using C#

// What ever we will get from task , its going to cal task value in task1 and process the final result.

 var task = Task<int>.Run(() => {
                 return  Enumerable.Range(1, 1000).Count(n => n / 2 == 2);
           });
            task.ContinueWith((task1) =>
            {
                if (task1.Result < 10)
                {
                 
                    Console.WriteLine(task1.Result);
                }
                else
                {
                    if (task1.IsFaulted == true) // Is IsFaulted used to check Exception in Task
                    {
                       foreach(var d in task1.Exception.Flatten().InnerExceptions)
                       {
                           Console.WriteLine(d.Message);
                       }
                   
                    }
                    else
                    {
                        Console.WriteLine(task1.Result);
                    }
                   
                }
            }).Wait(); // Wait going to wait finished his work and comeback with final result.
                              suppose if am not going to put wait here , that task is not going wait finished his work and he move to next line , with out giving output. 

No comments:

Post a Comment