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<Task> asynctasks = new List<Task>();
asynctasks.Add(cmd.ExecuteNonQueryAsync());
Task.Factory.StartNew(() => closeConnectionOnFinish(asynctasks, connection));
}
catch (Exception ex)
{
writeExceptionToLogFile(ex);
}
}
And the closeConnectionOnFinish
:
public async void closeConnectionOnFinish(List<Task> _tasks, SqlConnection connection)
{
try
{
await Task.WhenAll(_tasks);
connection.Close();
}
catch (Exception ex)
{
writeExceptionToLogFile(ex);
}
}