0

I'm looking to combine an async fill operation with disposable.

class G 
{
    SqlConnection connection
    SqlCommand command;

    IAyncResult Begin(string connectionString)
    {
     this.connection = new SqlConnection(connectionString);
     this.command = connection.CreateCommand();
     result = command.BeginExecuteReader();
    }
    
    void End(IAsyncResult result)
    {
     SqlDataReader reader = this.command.EndExecuteReader();
     DataTable table = new DataTable(); // ..just as an example
     table.Load(reader);
     reader.Close();
     connection.Close();
    }
}

The problem is that the connection never gets disposed.
I am trying to figure out how to wrap this in a using statement or dispose of the connection in another way.
Should I create an outer class with a connection that calls this class or can it be done somewhere in here ?

heyNow
  • 866
  • 2
  • 19
  • 42
  • 1
    Call `Dispose` in `End`? Though why use `IAsyncResult`? This is from .NET 1.0 days and has long been superseded by much more user friendly async programming models - `Task` with `async`/`await`. See https://stackoverflow.com/questions/12750532/what-are-the-strengths-of-the-iasyncresult-pattern – Charles Mager Apr 07 '22 at 19:57
  • I guess I was looking for a general way to combine disposable and async style, is the `Dispose` how its normally done ? or can a `using` statement be applied somewhere ? – heyNow Apr 07 '22 at 20:18
  • If you use the more modern and idiomatic async/await, you can just wrap your async call in a using block as you would writing synchronous code. You can't do that here, you'd have to explicitly call dispose. – Charles Mager Apr 07 '22 at 20:23
  • 1
    Here's a recent and useful article on using async/await with disposable objects: https://www.c-sharpcorner.com/article/using-asyncawait-with-disposable-objects/ – Matthew Watson Apr 07 '22 at 20:50

0 Answers0