-3

I Have the following code, the exception thrown by methodThatThrowsException get silent, how can I throw the exception ?

TaskScheduler scheduler = TaskScheduler.FromCurrentSynchronizationContext();
CancellationToken token = new CancellationToken();

Task task = Task.Factory.StartNew(MethodThatThrowsException)
                        .ContinueWith(t => { throw t.Exception; }, token, TaskContinuationOptions.OnlyOnFaulted, scheduler)
                        .ContinueWith(w => Vm.StatusMessage.StopProgressBar(), token, TaskContinuationOptions.OnlyOnRanToCompletion, scheduler);
Anas
  • 5,622
  • 5
  • 39
  • 71
  • Please see Exception Handling in TPL at; https://msdn.microsoft.com/en-us/library/dd997415%28v=vs.110%29.aspx – Teoman shipahi May 19 '15 at 20:19
  • Why the downvotes, it's been 2 hours that i'm looking for a solution, couln't find the answer on Stack Overflow or else where? Thanks to give the reason for downvotes so I can edit my question accordingly.. – Anas May 19 '15 at 20:39
  • Seems like if you google your question with your exact title you will get this SO answer http://stackoverflow.com/questions/6982294/why-doesnt-my-process-terminate-when-task-has-unhandled-exception and it has same reference link that I gave you. – Teoman shipahi May 19 '15 at 20:42

1 Answers1

1

You can receive the exception of the task by accessing the task.Exception property.

   Task task = Task.Factory.StartNew(MethodThatThrowsException)
                    .ContinueWith(t => { throw t.Exception; }, token, TaskContinuationOptions.OnlyOnFaulted, scheduler)
                    .ContinueWith(w => Vm.StatusMessage.StopProgressBar(), token, TaskContinuationOptions.OnlyOnRanToCompletion, scheduler);

   System.Exception yourException = task.Exception;
Cadburry
  • 1,844
  • 10
  • 21