C# 将 using 语句与 IAsyncReader 结合使用

发布于 2025-01-19 18:20:28 字数 693 浏览 2 评论 0原文

我希望将异步填充操作与一次性填充操作相结合。

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();
    }
}

问题在于连接永远不会被处置。
我试图弄清楚如何使用语句或以另一种方式处理连接将其包裹在中。
我应该创建一个带有连接的外部类,该连接称为此类,还是可以在此处的某个地方完成?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文