Not logged in - Login
< back

Trigger other tasks after task is complete or had exception

The following example shows how to start a task in a separate thread. Then, using the 'ContinueWith()' function, fire another task depending on if the first task had an unhandled exception or if the task completed without any unhandled exceptions.

[[[code lang=c#|private

private void button1_Click(object sender, EventArgs e)
 
{
  System.Diagnostics.Debug.WriteLine("button System.Diagnostics.Debug.WriteLine("buttonclicked");

  System.Threading.Tasks.Task<int> clicked");ret1 = System.Threading.Tasks.Task.Run(() => this.Task1(this.txtInput.Text));

  // run this task if we had any exceptions.
  var c1 = ret1.ContinueWith<decimal>((antecedant) => 
    this.Task2("error", antecedant), TaskContinuationOptions.OnlyOnFaulted);
  // run this task if we did NOT have any exceptions.
  var c2 = ret1.ContinueWith<decimal>((antecedant) => 
    this.Task3("success", antecedant), TaskContinuationOptions.NotOnFaulted);

  System.Diagnostics.Debug.WriteLine("Exiting Button1_click()");
}

private int Task1(string s)
{
  System.Diagnostics.Debug.WriteLine("Starting Task1");

  // simulate some work
  System.Threading.Thread.Sleep(5000);

  // do something with the string that was passed in.
  int y = 5;

  int x = 0;
  // attempt to convert the string that was passed in to an integer.
  x = Convert.ToInt32(s);

  // divide by the value that was passed in.
  int z = y / x;

  // simulate some more work
  System.Threading.Thread.Sleep(5000);

  System.Diagnostics.Debug.WriteLine("About to finish Task1");

  return z;
}

private decimal Task2(string s, Task<int> antecedant)
{
  System.Diagnostics.Debug.WriteLine("Inside Task2- had exception.");

  // do something with the string that was passed in.
  decimal d = 5;
  if (string.IsNullOrEmpty(s))
  {
       d = 0;
  }
  else
  {
       d = (decimal)s.Length;
  }

  // write the exception messages to the debug output window.
  System.Diagnostics.Debug.WriteLine(antecedant.Exception.Message);
  foreach (var ex in antecedant.Exception.InnerExceptions)
  {
       System.Diagnostics.Debug.WriteLine(ex.Message);
  }

  return d;      
}

private decimal Task3(string p, Task<int> antecedant)
{
  decimal d = 5;      

  System.Diagnostics.Debug.WriteLine("Inside Task3- no exceptions.");

  return d;
}

System.Threading.Tasks.Task