0

I am using the following way of querying in dapper on a MySQL database.

using (var db = new MySqlConnection(ConfigurationHandler.GetSection<string>(StringConstants.ConnectionString)))
{
    resultSet = db.Execute(UpdateQuery, new { _val = terminalId }, commandType: CommandType.Text);
    db.Close();//should i call this or not
    db.Dispose();//should i call this or not
}

Is it a good way of explicitly calling db.close and db.dispose? My application could be handling 100's of requests per second.

Kamran Shahid
  • 3,954
  • 5
  • 48
  • 93

1 Answers1

3

A using block is a convenience arround the IDisposable interface. It ensures that the dispose method is called at the end of the block.

See: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement.

In your case you can remove the explicit calls to db.Close() and db.Dispose() because you are not re-using the connection object.

using (var db = new MySqlConnection(ConfigurationHandler.GetSection<string>(StringConstants.ConnectionString)))
                {
                    resultSet = db.Execute(UpdateQuery,
                        new { _val = terminalId }, commandType: CommandType.Text);
                }

The following link provides further details about .Close vs .Dispose: https://stackoverflow.com/a/61171/1028323

Alex
  • 7,901
  • 1
  • 41
  • 56
  • 2
    Also, if your database driver (read: nuget package for mysql) supports connection pooling, then this practice will allow your app_pool to re-open the connection within a timespan without having to re-connect. -- which is handy and performant. – JasonInVegas Sep 17 '19 at 21:15
  • Thanks Alex and Jason. I am doing exactly like this with about 100 connections in pool – Kamran Shahid Sep 19 '19 at 14:46