Finding a way for using and async to be friends

Most people have discovered using and async are not good friends because often the one execution path disposes of the connection while another is still trying to use it.

So I came up with...

static async public Task<TResult> AsyncUsingConnection<TResult>(string connectionString,Func<SqlConnection, Task<TResult>> functiod) 
    {
        TResult result;
        SqlConnection connection = null;
        try
        {
            connection = new SqlConnection(connectionString);
            connection.Open();
            var resultTask = functiod(connection);
            
            resultTask.ContinueWith(t => { connection?.Dispose();
                connection = null;
            });
            return await resultTask;
        }
        catch (Exception ex)
        {
            connection?.Dispose();
            connection = null;
            throw;
        }
    }

which allow me to write..

AsyncUsingConnection("myconnectionString",async (connection)=> {

    SqlCommand cmd=new SqlCommand("Select * from foo");
    var reader= await cmd.ExecuteReaderAsync();
    while( await reader.ReadAsync() ) {
        ....    
    };
    reader.Close();
);

Lets ignore the fact the in reality I also need to dispose the DataReader ( just for clarities sake we'll only focus on one IDisposable),

Firstly my code analysis engine besides wanting to destroy the readability by wanting to liberally sprinkle ConfigureAwaits(false) everywhere.

But it also keeps suggesting I await the continueWith ; now my thinking is that I create the resultTask as the result of the function, I then attach a Continue with to dispose the connection when resultTask completes, and only then do I await resultTask and return the value ( while the continueWith tidies up);

Have I done this right ? or is there anything I could do better/ more robustly.



Read more here: https://stackoverflow.com/questions/67943832/finding-a-way-for-using-and-async-to-be-friends

Content Attribution

This content was originally published by Barry Wimlett at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: