0

问: 有没有办法阻止Command.ExecuteNonQuery()在它完成之前停止它,而不使用超时?

我创建了一个存储和运行 sql 语句的多线程 MySQL 程序。允许一组事务同时运行(因为它们不修改同一张表)。我不得不禁用超时(将其设置为 0),因为某些 SQL 语句可能需要几分钟才能运行。
当我想停止查询时,问题就来了。现在我必须等到当前的 SQL 语句完成(就像我说的可能需要几分钟)。

根据我现有的知识,以下是有效的代码(帮助他人):

MySqlConnectionStringBuilder ConnectionString = new MySqlConnectionStringBuilder();
ConnectionString.Server = ServerName;  // ServerName is a user defined string
ConnectionString.Database = DatabaseName; // DatabaseName is a user defined string
ConnectionString.UserID = UserName; // UserName is a user defined string
if (!Password.Equals(string.Empty)) // Password is a user defined string
{ ConnectionString.Password = Password; } // If Password string is not empty, then add it.
ConnectionString.AllowUserVariables = true; 

using (MySqlConnection connection = MySqlConnection(ConnectionString))
{
   try
   {
       connection.Open();
      DBTransaction Trans = connection.BeginTransaction();

       using (MySqlCommand Command = connection.CreateCommand())
       {
              foreach(String SQLCommandString in SQLCommands) // SQLCommands is user defined List<String>
              {
                   try
                   {
                          Command.CommandText = SQLCommandString; // SQLCommandString is a user defined string ex "UPDATE MyTable SET MyVar = 3 WHERE id = 3;"
                         NumOfRecordAffected = Command.ExecuteNonQuery();
                   }
                   catch (MySql.Data.MySqlClient.MySqlException ex)
                   {
                         Trans.RollBack();
                         // If code reaches here then there was a problem with the SQLCommandString executing.
                         throw ex;
                   }
                   catch (Exception ex)
                   {
                           // There was a problem other than with the SQLCommandString.
                           throw ex;
                   }
              }
       }
       Trans.Commit();
 }
4

1 回答 1

1

您不能在单线程应用程序中执行此操作,因为在 a) 查询完成执行或 b) 异常强制控制返回之前,控制不会返回。

相反,您可以在工作线程中启动和执行所有事务,并在需要时关闭来自原始线程的连接。调用MySqlConnection.Close()将回滚任何待处理的事务。

于 2013-04-10T16:31:58.850 回答