Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何让C#ExecuteReader抛出异常而不是挂起_C#_Mysql_.net 4.0 - Fatal编程技术网

如何让C#ExecuteReader抛出异常而不是挂起

如何让C#ExecuteReader抛出异常而不是挂起,c#,mysql,.net-4.0,C#,Mysql,.net 4.0,我打开了一个应用程序,它调用了使用“FOR UPDATE”执行选择-锁定行 当第二个应用程序尝试访问同一行时,该应用程序将挂起(直到超时): 根据SqlException下的描述: 对锁定行执行命令时发生异常 这就是我想要的——立即得到一个例外。 我试图更改命令超时,但这只是给出了TimeoutException,并没有解释确切的原因。您尝试过使用try-and-catch吗 var connection = new MySqlConnection(connectionString); try

我打开了一个应用程序,它调用了使用“FOR UPDATE”执行选择-锁定行

当第二个应用程序尝试访问同一行时,该应用程序将挂起(直到超时):

根据SqlException下的描述:

对锁定行执行命令时发生异常

这就是我想要的——立即得到一个例外。
我试图更改命令超时,但这只是给出了TimeoutException,并没有解释确切的原因。

您尝试过使用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;
        }

SQLException SQL连接的默认超时时间大约为15或30秒。当您的代码试图读取数据时,它会等待应答或超时。一种方法是减少超时时间并尝试重新连接,同时刷新程序(我不确定这有多实用-只有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.
}

如果您确实想要“锁定行”消息,您可以在15(或您选择的任何数量)1秒超时后执行此操作。

是-抱歉,代码太简单了。一切都在尝试中。问题是程序挂起在command.ExecuteReader行上,直到超时。然后一个超时异常是thrownCheck这个希望它能帮助你不,这是一个非常通用的解决方案,它只会告诉您是否发生了超时-它会引发超时异常,而不是更具体的SQL相关异常。我的想法是缩短超时时间,尝试几个程序可以更新的连接,而不是等待15或30秒。您还可以缩短超时时间,然后捕获异常。在没有异步连接或多线程的情况下,程序将以任意方式手动,因为在超时时间过去之前,它将一直等待答案,唯一的问题是它将被冻结多长时间。遗憾的是,除此之外,我无能为力。您正在引用与
SqlCommand.ExcecuteReader()
相关的MSDN文档。在代码中,您使用的是
MySqlCommand.ExcecuteReader()
,据我所知,它不是.NET Framework的一部分。类
MySqlCommand
开发者的具体文档说明了什么?
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.
}