简体   繁体   English

在ASP.NET中使用MySql:关闭连接是否真的释放表锁?

[英]Using MySql in ASP.NET: Does closing a connection really release table locks?

I'm working on an ASP.NET application where, as part of some logic, I want to lock some tables and do work on them. 我正在开发一个ASP.NET应用程序,作为某些逻辑的一部分,我想锁定一些表并对其进行处理。 The method runs in a separate thread running as a kind of background task, spawned via a Task. 该方法在单独的线程中运行,该线程作为一种后台任务运行,并通过Task产生。 The problem comes in with the error handling... 问题来自于错误处理...

The code looks more or less like this: 代码大致如下所示:

MySqlConnection connection = new MySqlConnection(ConfigurationManager.AppSettings["prDatabase"]);
try
{
    connection.Open();
    MySqlCommand lock_tables = new MySqlCommand(Queries.lockTables(), connection);
    lock_tables.ExecuteNonQuery();

    // do a bunch of work here

    MySqlCommand unlock_tables = new MySqlCommand(Queries.unlockTables(), connection);
    unlock_tables.ExecuteNonQuery();
}
catch (MySqlException mex)
{
    // Mostly error logging here
}
finally
{
    connection.Close();
}

Pretty simple stuff. 很简单的东西。 Everything works fine and dandy assuming nothing goes wrong. 假设一切正常,一切正常且正常。 That's a terrible assumption to make, though, so I deliberately set up a situation where things would foul up in the middle and move to the finally block. 但是,这是一个可怕的假设,所以我特意设置了一种情况,其中事情会在中间陷入困境,然后转移到最后一块。

The result was that my table locks remained until I closed the app, which I learned by trying to access the tables with a different client once the method completed. 结果是我的表锁一直保持到我关闭应用程序为止,方法完成后,我尝试通过其他客户端访问表来了解这一点。 Needless to say this isn't my intention, especially since there's another app that's supposed to access those tables once I'm done with them. 不用说,这不是我的意图,尤其是因为有另外一个应用程序可以在我处理完这些表后访问它们。

I could quickly fix the problem by explicitly releasing the locks before closing the connection, but I'm still left curious about some things. 我可以通过在关闭连接之前显式释放锁来快速解决问题,但是我对某些事情仍然感到好奇。 Everything I've read before has sworn that closing a connection should implicitly release the table locks. 我之前读过的所有内容都发誓说,关闭连接应该隐式释放表锁。 Obviously in this case it isn't. 显然在这种情况下不是。 Why is that? 这是为什么? Does connection.Close() not actually completely close the connection? connection.Close()确实不能完全关闭连接吗? Is there a better way I should be closing my connections? 有没有更好的方法来关闭我的连接?

Try wrapping your Connection and MySqlCommand instance in a using statement. 尝试在using语句中包装Connection和MySqlCommand实例。 That will release the objects as soon as it leaves the brackets. 一旦离开括号,这将释放对象。

    using(MySqlConnection conn = new MySqlConnection(connStr))
{
   conn.Open();
   using(MySqlCommand command  = new MySqlCommand("command to execute",conn))
{
   //Code here..
}

}

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

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