Closing SQL connection for async operations The following code executes asynchron on the SQL database. Is the closing of the connection implemented in the right way? Are there any missing features regarding connection handling which need to be added?

public void deleteData(Node node, User user)
        {
            SqlConnection connection = getConnection();
            connection.Open();
            string query = "DELETE FROM NodeUserData WHERE node = @nodeId and userId = @userId;";
            SqlCommand cmd = new SqlCommand(query, connection);
            cmd.CommandType = CommandType.Text;

            try
            {
                cmd.Parameters.AddWithValue("@nodeId ", node.id);
                cmd.Parameters.AddWithValue("@userId", user.id);

                List&lt;Task&gt; asynctasks = new List&lt;Task&gt;();
                asynctasks.Add(cmd.ExecuteNonQueryAsync());
                Task.Factory.StartNew(() =&gt; closeConnectionOnFinish(asynctasks, connection));

            }
            catch (Exception ex)
            {                
                writeExceptionToLogFile(ex);
            }       
        }


And the closeConnectionOnFinish:

public async  void closeConnectionOnFinish(List&lt;Task&gt; _tasks, SqlConnection connection)
        {
            try
            {
                await Task.WhenAll(_tasks);
                connection.Close();
            }
            catch (Exception ex)
            {
                writeExceptionToLogFile(ex);
            }
        }
No that isn't right. If your query throws an error you won't be closing the connection. Swallowing exceptions like that (even though you're logging it) is generally bad as well. How does the user know anything has gone wrong?

If you can, just use async and await with a using:

public async Task DeleteDataAsync(...)
{
     using (var connection = GetConnection())
     using (var cmd = /* ... */)
     {
         // ... trimmed
         await cmd.ExecuteNonQueryAsync();
     }
}


If you can't do that (I don't know why you couldn't) then you could do this:

cmd.ExecuteNonQueryAsync().ContinueWith(_ =&gt; connection.Close());


But you should be waiting for that task to finish.



Your naming is non standard: methods should be PascalCase.



async void is generally bad - there's no way for the caller to wait until the work is finished. You shouldn't use async void methods (except for event handlers).



Async methods should have the suffix Async and return a Task or Task&lt;T&gt;.



Don't use Task.Factory.StartNew unless you want to specify advanced options; use Task.Run. However, don't use Task.Run for fake asynchrony - you'll just slow things down.