Send feedback on this topic.
Teradata.Client.Provider
Command Execution and Cancellation using the Task-based Asynchronous Pattern
.NET Data Provider for Teradata > Developer's Guide > Working with the Data Provider Features > Asynchronous Support Overview > Asynchronous Command Execution Overview > Command Execution and Cancellation using the Task-based Asynchronous Pattern

TdCommand supports the Task-based Asynchronous Pattern (TAP) of the .NET Framework 4.5. These methods return a System.Threading.Tasks.Task that may execute asynchronously.

The following asynchronous TdCommand methods are supported:

Cancellation

Each method takes an optional System.Threading.CancellationToken that can be used to request cancellation of the operation if it is taking too long. If the task is canceled before the request is submitted to Teradata, the request will not be submitted. If the task is canceled after the request was submitted to Teradata, the request will be Canceled (Aborted) and the task will throw a TdException ("[112002] Request has been canceled by user"). The task will not be transitioned to the TaskStatus.Canceled state.

The following example illustrates how an application could call one of these methods and then attempt to cancel it:

C#
Copy Code
public void CancelDuringNextResult(string connectionString, string commandText)
{
    using (TdConnection cn = new TdConnection(connectionString))
    {
        cn.Open();

        using (TdCommand cmd = new TdCommand(commandText, cn))
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Task<TdDataReader> t = cmd.ExecuteReaderAsync(cts.Token);

            // do some other asynchronous work

            try
            {
                while (t.IsCompleted == false)
                {
                    Thread.Sleep(1000);
                    cts.Cancel(); // Cancel the operation
                }

                // If the task is canceled after the request was sent to the SQL Engine,
                // Task.Wait() and Task.Result will throw an exception.
                // Task.IsCanceled may not be used if the cancellation results in a TdException

                TdDataReader reader = t.Result;
                // The task completed before it could be canceled --
                // use the reader to process the data.
            }
            catch (AggregateException e)
            {
                TdException t = e.InnerException as TdException;
                if (t != null && t.Errors[0].Number == 112002)
                {
                    // The task was canceled after the request was sent to the SQL Engine.
                    // The request was Canceled (Aborted) as part of the task cancellation.
                    // Handle the "Request has been canceled by user" error here.
                }
                else
                {
                    throw;
                }
            }
        }
    }
}