Saturday, February 28, 2015

Aggregation Exceptions In Task


using System.Windows.Forms;
using System.Threading; //add it to the .Net

namespace AggregationExceptionsInTask
{

        //When running the program, run it outside visual studio

    public partial class Form1 : Form
    {
        //Note: we created a RichTextBox1 and a Button in the design
        //Exception thrown from tasks and/or child tasks are bundled into a single exception called the AggregationException. The AggregationException can be taught by calling source.
        //The AggregationException is more than a container or a collection of all the exceptions thrown inside of the running tasks
        //The calling source could catch the AggregateEception when it uses the Wait/WaitAll method
        // or
        //access the Result property of tasks(childtask.Result)
        //for the calling source to catch the ArgumentException it needs to have the wait/Waitall statment in a try/catch blocks

        public Form1()
        {
            InitializeComponent();
        }

        //button name = Catch Exception Thrown From Tasks
        private void btnTaskAggrgatedException_Click(object sender, EventArgs e)
        {
            //first create a task schedule
            TaskScheduler uits = TaskScheduler.FromCurrentSynchronizationContext();

            //Create and start a parent task
            //then create and start multiple child tasks/or nested tasks

            Task parent = Task.Factory.StartNew(() => //...parent task will try to display something in the screen
            {
                //assuming that each inner task will perform some work
                //  and may throw some exceptions under some condition
                //  in this example, each inner task will throw and exception
                Task innerTask1 = Task.Factory.StartNew(() =>
                {
                    throw new FormatException("Invalid data \n");
                });
                Task innerTask2 = Task.Factory.StartNew(() => //..you can put as many as task as you want....just changed the name ex. innetask3,innertask4
                {
                    throw new InvalidOperationException("\nAttemp to run an invalid Expection");
                });

                Task innerTask3 = Task.Factory.StartNew(() =>
                {
                    throw new IndexOutOfRangeException("use and invalid Index");
                });
                //we want the calling source (in this case parent task, to catch the //exception that the inner task may throw
                //     the parent task need to use the Wait or WaitAll method in a try/catch block

                //we use a try/catch here
                try
                {
                    //cause the parent to wait for all inner tasks
                    Task.WaitAll(innerTask1, innerTask2, innerTask3);
                }
                catch (AggregateException aggrEx)
                {
                    //since the aggregation exception is just a collection of all exceptions thrown inside the inner tasks, use foreach to sequence thru them
                    foreach (Exception exception in aggrEx.InnerExceptions)
                    {
                        richTextBox1.AppendText(String.Format("{0} : {1}", exception.GetType().Name, exception.Message));
                    }
                }
            }, CancellationToken.None, TaskCreationOptions.None, uits);//if you put a comma you will see all the taskschedulers cancellations...add the using system.threading;
        }
    }
}
//Next week we will work on the Parallel Class.... https://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel%28v=vs.110%29.aspx

No comments:

Post a Comment