I have a strange problem. The exception thrown by Task is not always handled independently, how can I handle it.
I try this:
http://msdn.microsoft.com/en-us/library/dd997415%28v=vs.110%29.aspx
private class MyCustomException : Exception { public MyCustomException(String message) : base(message) { } } public static void Main() { var task1 = Task.Factory.StartNew(() => { throw new MyCustomException("I'm bad, but not too bad!"); }); try { task1.Wait(); } catch (AggregateException ae) { // Assume we know what going on with this particular exception. // Rethrow anything else. AggregateException.Handle provides // another way to express this. See later example. foreach (var e in ae.InnerExceptions) { if (e is MyCustomException) { Console.WriteLine(e.Message); } else { throw; } } } Console.Read(); }
http://dotnetcodr.com/2014/02/11/exception-handling-in-the-net-task-parallel-library-with-c-the-basics/
http://blogs.msdn.com/b/pfxteam/archive/2010/08/06/10046819.aspx
var task = Task.Factory.StartNew(() => this.InitializeViewModel(myViewModel)); task.ContinueWith(o => MyErrorHandler(task.Exception), TaskContinuationOptions.OnlyOnFaulted);
and check out many other similar questions in StackOverflow. But this is always the same: the exception is not handled. It is not processed in these primitive code snippets! I think there is some magic here ... I am working on .Net Framework 4.0
Meanwhile, the only way to handle the exception that works for me is:
Task.Factory.StartNew(() => { try { //do something that thrown exception } catch (Exception) { } });
c # exception exception-handling task-parallel-library
monstr
source share