简体   繁体   English

如何使C#ExecuteReader引发异常而不是挂起

[英]How to get C# ExecuteReader to throw exception instead of hang

I have an application open which has called performed a SELECT using "FOR UPDATE" - locking the row. 我有一个打开的应用程序,它使用“ FOR UPDATE”调用执行SELECT-锁定行。

When a second application tries to access the same row the application hangs (untill it times out) on: 当另一个应用程序尝试访问同一行时,该应用程序挂起(直到超时):

// Simplified code
var connection = new MySqlConnection(connectionString);
connection.Open();

var transaction = connection.BeginTransaction();

MySqlCommand command = new MySqlCommand(sqlQuery, connection, transaction);
MySqlDataReader dataReader = command.ExecuteReader(); // HANGS

According to the documentation it says under SqlException: 根据文档,它在SqlException下显示:

An exception occurred while executing the command against a locked row 针对锁定的行执行命令时发生异常

This is what I would like - to get an exception immediately. 这就是我想要的-立即获得例外。 I tried to change the command timeout, but this just gives a TimeoutException and nothing explaining that the accurate reason. 我试图更改命令超时,但这只是给出TimeoutException而没有解释确切原因。

Have you tried using try and catch? 您是否尝试过使用try and catch?

var connection = new MySqlConnection(connectionString);
try

{


connection.Open();

var transaction = connection.BeginTransaction();

MySqlCommand command = new MySqlCommand(sqlQuery, connection, transaction);
MySqlDataReader dataReader = command.ExecuteReader(); 
}
catch (Exception)
        {
            throw;
        }

SqlExceptionThe default timeout period for SQL connection is something like 15 or 30 seconds. SqlExceptionSQL连接的默认超时时间约为15或30秒。 When your code attempts to read the data it waits for an answer or timeout. 当您的代码尝试读取数据时,它将等待答案或超时。 One way of doing this (I'm not sure how practical it is though - only a beginner at SQL) is reducing the timeout period and attempting to reconnect, while refreshing the program: 一种执行此操作的方式(虽然我不确定它的实用性-仅是SQL的初学者),但是在刷新程序的同时减少了超时时间并尝试重新连接:

connection.ConnectionTimeout = 1; //timeout in seconds
//initialize command, connection etc
bool commited;
while(!commited){
   try{
      MySqlDataReader dataReader = command.ExecuteReader(); 
      commited = true;
   }catch(SqlException e) {
      commited = false;
   }
   //code to force program update.
}

And if you really want the "locked row" message, you can do it after 15 (or whatever amount you choose) of 1 second timeouts. 而且,如果您确实想要“锁定行”消息,则可以在15秒(或您选择的任何数量)的1秒超时后执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM