I'm having problems with TPL programming.
I'm getting UnobservedTaskException while using @h4165f8ghd4f854d6f8h solution on [ https://mcmap.net/q/17085/-a-task-39-s-exception-s-were-not-observed-either-by-waiting-on-the-task-or-accessing-its-exception-property-as-a-result-the-unobserved-exception-was/11830087#11830087 ] to handle exceptions but still getting UnobservedTaskException.
I added the following code before starting tasks too:
TaskScheduler.UnobservedTaskException += (sender, e) =>
{
e.SetObserved();
throw e.Exception;
};
but [ https://mcmap.net/q/17086/-exception-thrown-in-task-thread-not-caught-by-unobservedtaskexception ] telling it won't catch every TPL unhandled exception.
I want propagate exceptions until reach top of stack then deal with it.
Can someone help me????
@Jon Skeet
Hi, I did a smaller repro, thanks for checking
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.tplTestOne();
}
public void tplTestOne()
{
TaskScheduler.UnobservedTaskException += (sender, e) =>
{
e.SetObserved();
throw e.Exception;
};
Task tsk_1 = MyClassHere.createHandledTask(() =>
{
double x = 1;
x = (x + 1) / x;
}, false);
Task tsk_2 = MyClassHere.createHandledTask(() =>
{
double y = 0;
throw new Exception("forced_divisionbyzerodontthrowanymore_test"); // here -> System.Exception was unhandled by user code
}, true);
Task tsk_3 = MyClassHere.createHandledTask(() =>
{
double z = 1;
z = (z + 1) / z;
}, true);
Task tsk_4 = MyClassHere.createHandledTask(() =>
{
double k = 1;
k = (k + 1) / k;
}, true);
Console.ReadLine();
}
}
public static class MyClassHere
{
public static void waitForTsk(Task t)
{
try
{
t.Wait();
}
catch (AggregateException ae)
{
ae.Handle((err) =>
{
throw err;
});
}
}
public static void throwFirstExceptionIfHappens(this Task task)
{
task.ContinueWith(t =>
{
var aggException = t.Exception.Flatten();
foreach (var exception in aggException.InnerExceptions)
{
throw exception; // throw only first, search for solution
}
},
TaskContinuationOptions.OnlyOnFaulted); // not valid for multi task continuations
}
public static Task createHandledTask(Action action)
{
return createHandledTask(action, false);
}
public static Task createHandledTask(Action action, bool attachToParent)
{
Task tsk = null;
if (attachToParent)
{
TaskCreationOptions atp = TaskCreationOptions.AttachedToParent;
tsk = Task.Factory.StartNew(action, atp);
}
else
{
tsk = Task.Factory.StartNew(action);
}
tsk.throwFirstExceptionIfHappens();
return tsk;
}
}
Thanks