user437631
user437631

Reputation: 1112

handling exceptions on tasks on .net 4.0

I'm getting an odd exception on task creation in .net 4.0.

I'm getting the exception on windows service with a Global Updomain unhandled exceptions handler so I don't have the exact stack: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property.

I think it occurs on the following code section:

  for (int i = 0; i < _workers.Length; ++i)
        {
            int j = i;  // copy 

            Task t1 = Task.Factory.StartNew(() =>
            {
                try
                {
                    if (!_workers[j].Join(4000))
                        LogWriter.Trace("Failed to join thread", "ThreadFailureOnDispose");
                }
                catch (Exception ex)
                {
                    OnLogged(ex.Message + ex.StackTrace);
                }
            });

        }

Anyone got an idea? Is it something with the aggregated exception feature?

Upvotes: 0

Views: 440

Answers (3)

Brian
Brian

Reputation: 118895

See the bottom of

http://blogs.msdn.com/b/pfxteam/archive/2009/10/27/9913610.aspx

for some useful info.

I don't think this is coming from the code you have showed in the question.

Upvotes: 1

user437631
user437631

Reputation: 1112

well, I think that Task should catch AggregateExecption when using Parallel.For\Foreach as follows:

  try
        {
            Parallel.For(0, _workers.Length, i =>
            {

                DoWork(i);

            });

        }
        catch (AggregateException ex)
        {
            // Assume we know what's going on with this particular exception.
            // Rethrow anything else. AggregateException.Handle provides
            // another way to express this. See later example.
            foreach (var e in ex.InnerExceptions)
            {
                OnLogged(e.Message + e.StackTrace);
            }

        }

Upvotes: 0

Richard
Richard

Reputation: 109100

You should find the exception is of type AggregateException (for future reference include the exception type when asking questions—it is key information).

This includes the exceptions thrown in its InnerExceptions property.

Upvotes: 0

Related Questions