Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Task.ContinueWith on exception

I am trying to prevent a task from continuing if the first part fails.

My code looks like that:

Task listener = Task.Factory.StartNew(openConnection).ContinueWith((t) => listenForNumber());

    void openConnection()
    {
        try
        {
           //stuff
        }
        catch
        {
          //morestuff
        }
    }

    void listenForNumber()
    {
       //even more stuff
    }

Now listenForNuber() should not be executed if openConnection() enters the catch block

I tried ContinueWith((t) => listenForNumber(),TaskContinuationOptions.NotOnFaulted);

But no success, any help? :(

Thanks

like image 387
Ekoms Avatar asked Feb 10 '11 14:02

Ekoms


1 Answers

TaskContiuationOptions.NotOnFaulted will obviously have no effect unless your method has faulted, i.e. an exception thrown during its execution was unhandled.

In your catch block, you should re-throw the exception (and preserve the stack trace) using the throw; statement after you've performed your work (some clean-up maybe) - otherwise the exception won't be thrown again, so your method will not be considered as 'faulted'.

like image 109
ShdNx Avatar answered Sep 23 '22 10:09

ShdNx