asp.net.ph

SqlCommand.Cancel Method

System.Data.SqlClient Namespace   SqlCommand Class


Cancels the execution of an SqlCommand.

[ VB ]
NotOverridable Public Sub Cancel ( )

[ C# ]
public void Cancel ( );

[ C++ ]
public: __sealed void Cancel ( );

[ JScript ]
public function Cancel ( );

Implements

IDbCommand.Cancel

Remarks

If there is nothing to cancel, nothing happens. However, if there is a command in process, and the attempt to cancel fails, no exception is generated.

Example

The following example demonstrates the use of the Cancel method.

private SqlCommand _cmd;
// threads signal these when done
private AutoResetEvent _e1 = new AutoResetEvent ( false );
private AutoResetEvent _e2 = new AutoResetEvent ( false );

void IssueQuery ( ) {
   SqlDataReader r;
   int rows = 0;
   try {
      r = _cmd.ExecuteReader ( );
      do {
         while ( r.Read ( ) ) {
            rows++;
         }
      } while ( r.NextResult ( ) );
      Response.Write ( "FAILED: execution should not have finished, {0} rows read!", rows );
   }
   catch ( ) {
      Response.Write ( "PASSED:  Got expected exception!" );
   }
_e1.Set ( );
}

void CancelQuery ( ) {
   System.Threading.Thread.Sleep ( 500 );
   _cmd.Cancel ( );
   _e2.Set ( );
}

void CancelTest ( ) {
   SqlConnection conn = new SqlConnection (
      "Data Source=localhost; Integrated Security=SSPI;Initial Catalog=northwind;" );
   conn.Open ( );
   _cmd = new SqlCommand ( null, conn );

   AutoResetEvent [ ] evs = new AutoResetEvent [ 2 ];
   evs [ 0 ] = _e1;
   evs [ 1 ] = _e2;

   Thread t1 = new Thread ( new ThreadStart ( this.IssueQuery ) );
   Thread t2 = new Thread ( new ThreadStart ( this.CancelQuery ) );
   t1 = new Thread ( new ThreadStart ( this.IssueQuery ) );
   t2 = new Thread ( new ThreadStart ( this.CancelQuery ) );

   // cancel operation while results are coming back
   _cmd.CommandText = "SELECT * FROM orders, products";
   t1.Start ( );
   t2.Start ( );
   WaitHandle.WaitAll ( evs );
   conn.Close ( );
}
  C# VB

See Also

SqlCommand Members Skip Navigation Links




Home
Suggested Reading


Previous page Back to top Next page

© 2000-2010 Rey Nuñez All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note

You can help support asp.net.ph