0

This is an odd scenario, but I have a Task in an unknown state. What I'd like to do is to be able to if it becomes Faulted then cause an Application.UnhandledException. Rather than TaskScheduler.UnobservedTaskException which is what happens if I leave it alone.

await task does work however this code needs to run in .NET 4 without any extra dependencies. So in essence I need to recreate the effect of awaiting the task.

task.ContinueWith(t => {
        throw new InvalidOperationException();
    }, 
    CancellationToken.None, 
    TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
    SynchronizationContext.Current != null ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Current
);

The above code doesn't seem to do anything at the moment.

Any thoughts?

Nigel Sampson
  • 10,549
  • 1
  • 28
  • 31
  • Yes, that looks fine. Minus anybody being able to repro your problem from that snippet and you for some mysterious reason not using the return value of ContinueWith. Something like task = task.ContinueWith(...) – Hans Passant Dec 26 '15 at 23:02
  • Can you give more context? When do you expect the `InvalidOperationException` to be thrown? on which thread? – Yacoub Massad Dec 26 '15 at 23:25
  • What I'd like is the `InvalidOperationException` to happen on the UI thread and show up as an `Application.UnhandledException`. – Nigel Sampson Dec 26 '15 at 23:43
  • You can get close by enabling `ThrowUnobservedTaskExceptions` in `app.config` as described [here](http://stackoverflow.com/a/22395161/1768303). Note however `UnhandledException` will still be fired upon garbage collection rather than right on the spot (where exception was thrown). – noseratio Jan 05 '16 at 17:08

0 Answers0