Visual C# Developer Center > Visual C# Forums > Visual C# General > How to cancel transaction at SQL Server via C# code
Ask a questionAsk a question
 

AnswerHow to cancel transaction at SQL Server via C# code

  • Thursday, October 29, 2009 10:01 AMand85 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi.

    I'm try to modify this example from MSDN for my needs
    http://msdn.microsoft.com/en-us/library/1a674khd%28VS.80%29.aspx

    I have one thread for GUI and one thread for calculations.

    When user press cancel button, ExecuteReader must be stopped and transaction at server must be canceled.

    So if cancel button is pressed i'm not waiting for ending of ExecuteReader and call EndExecuteReader. But when call transaction Rollback, get error that timeout period is expired. But as you see CommandTimeout is very big.

    As workaround i tried to don't call Rollback. In this way transaction continue working at server for a long time (equal to durration of process without cancel ).

    How to cancel transaction at server?

    I rewrote few methods and got something like this:
    private
     void
     MyMethod(object
     sender, System.ComponentModel.DoWorkEventArgs e)
            {
                SetGuiState(false
    );
                string
     commandText = "MyCommand"
    
                
                RunCommandAsynchronously(commandText, GetConnectionString());
    
            }
    private
     void
     RunCommandAsynchronously(
            string
     commandText, string
     connectionString)
            {
                SqlConnection connection = new
     SqlConnection(connectionString);
    
                try
    
                {
                    SqlCommand command = new
     SqlCommand(commandText, connection);
                    
                    command.CommandTimeout = 6000;
    
                    connection.Open();
    
                    SqlTransaction transaction = connection.BeginTransaction("MyTran"
    );
    
                    command.Transaction = transaction;
    
                    IAsyncResult result = command.BeginExecuteReader();
    
                    while
     (!result.IsCompleted)
                    {
                       // if user pressed cancel
    
                        if
     (CancellationPending)
                        {
                            break
    ;
                        }
                    }
    
                    SqlDataReader reader = command.EndExecuteReader(result);
    
                     //if user pressed cancel
    
                     if
     (!CancellationPending)
                    {
                        DisplayResults(reader);
                        reader.Close();
                        transaction.Commit();
                    }
                    // if user dont pressed cancel
    
                    else
    
                    {
                        
                        reader.Close();
                        transaction.Rollback();
                    }
                }
                catch
     (SqlException ex)
                {
                    MessageBox.Show("Error: "
     + ex.Number + " "
     + ex.Message);
                }
                catch
     (InvalidOperationException ex)
                {
                    MessageBox.Show("Error: "
     + ex.Message);
                }
                catch
     (Exception ex)
                {
                    MessageBox.Show("Error: "
     + ex.Message);
                }
                finally
    
                {
                    connection.Close();
                }
            }
    
            private
     void
     DisplayResults(SqlDataReader reader)
            {
                while
     (reader.Read())
                {
                }
            }
    
            private
     string
     GetConnectionString()
            {
                return
     @"Persist Security Info=true;Integrated Security=false;server=MyServer;
                                Pwd=MyPassword;User Id=MyUser;Asynchronous Processing=true"
    ;
            }
    
    
    Thanks

    PS. SQL Server 2005 SP3. C#.NET 3.5

Answers

  • Wednesday, November 04, 2009 12:49 PMand85 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Thanks.
    I just  added Connection Timeout Keyword to my connection string and changed default value.
    • Marked As Answer byand85 Wednesday, November 04, 2009 12:49 PM
    •  

All Replies