A day with .Net

My day to day experince in .net

Exception handling in Task Parallel Library

Posted by vivekcek on May 31, 2012

The below code shows how to handle exception from parallel thread. In this case we handle exception from only one thread.

 var task1 = Task.Factory.StartNew(() =>;
                {
                    throw new Exception("throwing unhandled exception");

                }
                       );
                try
                {
                    task1.Wait();
                }
                catch (AggregateException ag)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Exception ex in ag.InnerExceptions)
                    {
                        sb.AppendLine(ex.Message);
                    }
                    MessageBox.Show(sb.ToString());
                }
                finally
                {
                    task1.Dispose();
                }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s