Search code examples
c#winformsms-accessoledb

Why does Oledb Connection.Close() take far too long to execute?


During development of a desktop app to connect to a local database, I moved the database to a network location and now every time I call Connection.Close() the program hangs for 5-15 seconds. I would see this problem very infrequently when the database was stored on the local computer, but now that it's on the network, it hangs almost every time I attempt a Close(). The first call I make to the database I don't even query it, it's just a test connection that I open and close to make sure the user can connect, but it still hangs far too long.

I've seen this question asked before, but no one can offer a suggestion or solution to fix other than 'try using() {} to have c# clean it up.' This does not affect the Close() time in any way.

Is there an option in the connection string to address this issue? Does anyone know why this is happening?

The connection string I use is:

CONNECTION_STRING = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=\\NEWTORK\Shared\Database\Database.accdb; Persist Security Info=False;"

private void

  Form_Login_Load(object sender, EventArgs e)
  {
    OleDbConnection Connection = new OleDbConnection();
    Connection.ConnectionString = CONNECTION_STRING;
    try
    {
      Console.Write("Connection Opening.....");
      Connection.Open();
      Console.WriteLine("Connection Opened");
      Console.Write("Writing Status Text.....");
      lbl_Status.Text = "Online";
      Console.WriteLine("Written Status Text");
      Console.Write("Connection Closing.....");
      Connection.Close();
      Console.WriteLine("Connection Closed");
    }
    catch (Exception Ex)
    {
      lbl_Status.Text = "Offline";
      lbl_Status.ForeColor = System.Drawing.Color.FromArgb(255, 0, 0);
      MessageBox.Show("Could not connect to Database");
    }
  }

In my output window, I see the opening messages and the writing status messages right away, but the app hangs just before the 'Console.Write("Connection Closing.....");' line. After 5-15 seconds, the close message appears in the window.

There are many connections in the app that do query the database and it seems to hang just before trying to close all of them as well. I do seems to notice that repeating the same query without closing the app sometimes results in quicker close times for the repeated close, but it always hangs during the first attempt for any query.


Solution

  • What ended up working for me: When I was getting long lag times for the Connection.Close() method, I was using the Microsoft Access database engine 2016 (x64). For an unrelated reason, I needed to uninstall the 2016 engine and go with the 2010 (x86) version. Now my Connection.Close() times are averaging ~40 ms which is perfectly acceptable for my application.