Trying to understand try/catch( AggregateException ) does not cancel my task.

  • Thread starter Thread starter m00n
  • Start date Start date
M

m00n

Guest
I'm trying to ramp up on Tasks and all that. I wanted to experiment with canceling a task. Inside UpdateText if i DO NOT use a try catch my cancel happens. However, if I put a try catch in the function, either inside or outside the for loop, my cancel is not being triggered. I even put a break point in catch block to see if it's being caught, but it's not. On my form, I have two buttons, one to start execution, one to cancel.

The entry into execution is RunningTwoTasksContinuationwhich gets called on a button click.


CancellationTokenSource cts;
CancellationToken ct;


public Form1( )
{
InitializeComponent( );

cts = new CancellationTokenSource( );
ct = cts.Token;
}

private void btnGo_Click( object sender, EventArgs e )
{
RunningTwoTasks( );
}


private void btnCancel_Click( object sender, EventArgs e )
{
cts.Cancel( );
}



private void RunningTwoTasksContinuation( )
{
ct = cts.Token;
var t1 = Task.Factory.StartNew (UpdateText, "ONE");

t1.ContinueWith( ant => UpdateText( "TWO" ), ct ).ContinueWith( ant => UpdateText( "THREE" ), ct );
}



private void UpdateText( object state )
{
ct.ThrowIfCancellationRequested( );
for( int i = 0; i < 500; i++ )
{
try
{
richTextBox1.Invoke( new Action( ( ) => richTextBox1.Text += "\n" + state + " " + i ) );
}
catch( AggregateException ex )
{
richTextBox1.Invoke( new Action( ( ) => richTextBox1.Text += "\n" + " ====== CANCELED ====== " ) );
}
}
}


Thanks for any help! Greatly appreciated.

Rick


Rick

Continue reading...
 
Back
Top